Gan all night wrote 30,000 words to explain all the commands, functions and operators of the SQL database clearly and clearly. The content is really rich. It is recommended to collect + three consecutive praises!

foreword

You may not be used to the habit of capitalizing SQL, but the real specification is to capitalize, so you should gradually get used to my explanation in capitalization. In all the following explanations, I will explain in the form of basic grammar, cases, and connections, so as to strengthen the use and understanding of each statement. This article was written by the author after a whole night of arranging it. I hope you will praise it for three consecutive times, thank you. Of course, with this article, you will completely master all the commands of mysql, and you will no longer have to buy or mess around with learning. The content of this article will temporarily explain the screening part of the database, because the initial introduction of the database such as creation, backup, etc. has been discussed. Magic Teleportation: Portal
The content of the portal includes:
insert image description here

The most important commands in MYSQL

SELECT 从数据库中提取数据
UPDATE  更新数据库中的数据
DELETE 从数据库中删除数据 
INSERT INTO 将新数据插入数据库
CREATE DATABASE 创建一个新的数据库
ALTER DATABASE 	修改数据库
CREATE TABLE 	创建一个新表
ALTER TABLE 	修改表
DROP TABLE		删除表
CREATE INDEX	创建索引(搜索键)
DROP INDEX	删除索引

SELECT statement

The SELECT statement is used to select data from the database. The returned data is stored in a result table called a result set.
SELECT syntax:

SELECT column1, column2, ...

Here, column1, column2, … are the field names of the table from which to select data. If you want to select all available fields in the table, use the following syntax:

SELECT * FROM table_name;

Suppose we already have a database Customers as follows:
insert image description here
SELECT COLUMN EXAMPLE
The following SQL statement selects the "CustomerName" and "City" columns from the "Customers" table:

SELECT CustomerName, City FROM Customers;

SELECT * Example
The following SQL statement selects all columns from the "Customers" table:

SELECT * FROM Customers;

Exercise Questions:
1- Get all the columns in the Customers table.

SELECT * FROM Customers;

2- Write a statement City select column from Customers table.

SELECT City FROM Customers;

3- Select all the distinct values ​​from the Country column in the Customers table. (I'll talk about it later, it doesn't matter if you don't understand)

SELECT DISTINCT	Country FROM Customers;

SELECT DISTINCT select different statements

The SELECT DISTINCT statement is only used to return distinct (different) values. In a table, a column often contains many duplicate values; sometimes you just want to list distinct (distinct) values.
SELECT DISTINCT syntax

SELECT DISTINCT column1, column2, ...
FROM table_name;

Let's also assume a Customers database:
insert image description here
SELECT without DISTINCT Example
The following SQL statement selects all (including duplicates) values ​​from the "Country" column of the "Customers" table:

SELECT Country FROM Customers;

SELECT DISTINCT example

SELECT DISTINCT Country FROM Customers;

The following SQL statement lists the number of distinct (different) customer countries:

SELECT COUNT(DISTINCT Country) FROM Customers;

Exercise:
1- Select all distinct values ​​Customers from the Country column in the table.

SELECT  DISTINC Country FROM Customers;

WHERE query targeting clause

The WHERE clause is used to filter records. It is used to extract only records that meet specified conditions.
WHERE syntax

SELECT column1, column2, ...
FROM table_name
WHERE condition;

Note: The WHERE clause is not only used in SELECT statements, it is also used in UPDATE, DELETE, etc.!
Let's assume that we still have such a database as Customers as follows:
insert image description here
WHERE clause example
The following SQL statement selects all customers from the country "Mexico" in the "Customers" table:

SELECT * FROM Customers
WHERE Country='Mexico';

Text and numeric fields
SQL requires single quotes around text values ​​(most database systems also allow double quotes). However, numeric fields should not be enclosed in quotes:

SELECT * FROM Customers
WHERE CustomerID=1;

Operators
in the WHERE clause The following operators can be used in the WHERE clause:
insert image description here
we can demonstrate the use of these symbols one by one, be patient
Suppose we have a database called Product:
insert image description here

Select all products with price 18 (=)

SELECT * FROM Products
WHERE Price = 18;       

Select all products with a price greater than 30 (>)

SELECT * FROM Products
WHERE Price > 30;

Select all products with price less than 30 (<)

SELECT * FROM Products
WHERE Price < 30;

Select all products with a price greater than or equal to 30 (>= )

SELECT * FROM Products
WHERE Price >= 30;

Select all products with price less than or equal to 30 ( <= )

SELECT * FROM Products
WHERE Price <= 30;

Select all products whose price is not equal to 18 (equivalent to !=)

SELECT * FROM Products
WHERE Price <> 18;

Select all products with prices between 50 and 60

SELECT * FROM Products
WHERE Price BETWEEN 50 AND 60;

Search all cities starting with the letter s from the Customers database above

SELECT * FROM Customers
WHERE City LIKE 's%';

Find all customers in Paris and London from the Customers database

SELECT * FROM Customers
WHERE City IN ('Paris','London');

The above is a demonstration of all symbols.
Let's do some more exercises to consolidate (we used the customers above)
1- Select all the records whose City column value is "Berlin".

SELECT * FROM Customers
WHERE City='Berlin';

2- Use the NOT keyword to select all records whose City is not "Berlin".

SELECT * FROM Customers
WHERE NOT City ='Berlin';

3- Select all records with CustomerID column value of 32.

SELECT * FROM Customers
WHERE CustomerID =12;

AND, OR, and NOT operators

The WHERE clause can combine AND, OR and NOT operations. The AND and OR operations are used to filter records based on multiple conditions:
The AND operation displays a record if all conditions are met and the AND is true.
The OR operation displays a record if any one of the conditions OR is true.
The NOT operation is displayed if the condition(s) are incorrect to record.
AND syntax

SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;

OR syntax

SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;

NOT syntax

SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;

Let's also assume the following "Customers" table:
insert image description here
AND Example
The following SQL statement selects all fields from Customers where the country is "Germany" and the city is "Berlin":

SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';

OR Example
Select all "Customers" with city "Berlin" OR "München":

SELECT * FROM Customers
WHERE City='Berlin' OR City='München';

NOT Example
to select fields from "Customers" whose country is not "Germany":

SELECT * FROM Customers
WHERE NOT Country='Germany';

Combine AND, OR and NOT
to select all fields from "Customers" where the country is "Germany"" and the city must be "Berlin" OR "München" (use parentheses to form complex expressions):

SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München');

Select all fields from "Customers" where the country is not "Germany" nor "USA"::

SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';

Exercise
Select all records with a City column value of 'Berlin' and a PostalCode column value of 12209.

SELECT * FROM Customers
WHERE City = 'Berlin'
AND PostalCode= 12209;

ORDER BY keyword

The ORDER BY keyword is used to sort the result set in ascending or descending order. ORDER BY By default, the keyword sorts records in ascending order. To sort records in descending order, use the DESC keyword.
ORDER BY syntax

SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

Let's also assume we have the "Customers" table as follows:
insert image description here
ORDER BY Example
Select all customers from the "Customers" table, sorted by the "Country" column:

SELECT * FROM Customers
ORDER BY Country;

ORDER BY DESC Example
Select all customers from the "Customers" table, sorted by DESCENDING by the "Country" column:

SELECT * FROM Customers
ORDER BY Country DESC;

ORDER BY Multiple Column Example
Selects all customers from the "Customers" table, sorted by the "Country" and "CustomerName" columns. This means it's sorted by country, but if some rows have the same country, it's sorted by CustomerName:

SELECT * FROM Customers
ORDER BY Country, CustomerName;

Select all customers from the "Customers" table, sorted by "Country" ascending and "CustomerName" columns descending:

SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;

Exercise
Select all records from the Customers table and sort the results alphabetically by the City column.

SELECT * FROM Customers
ORDER BY City;

INSERT INTO insert statement

The INSERT INTO statement is used to insert new records in the table.
INSERT Syntax
The INSERT INTO statement can be written in two ways:
1- Specify the column names and values ​​to insert:

INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

2- If you want to add values ​​for all columns of the table, you don't need to specify the column names in the SQL query. However, make sure that the values ​​are in the same order as the columns in the table. Here, the INSERT INTO syntax is as follows:

INSERT INTO table_name
VALUES (value1, value2, value3, ...);

Let's assume we still have the same Customers table:
insert image description here
INSERT Example
The following SQL statement inserts a new record in the "Customers" table:

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');

The run shows the following:
insert image description here
Did you notice that we didn't insert any numbers in the CustomerID field? The CustomerID column is an auto-incrementing field that will be automatically generated when a new record is inserted into the table.
Insert Data Only in Specified Columns
The following SQL statement will insert a new record, but only in the "CustomerName", "City" and "Country" columns (CustomerID is automatically updated):

INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');

After running it will display the following:
insert image description here
Exercise:
Insert a new record into the table.

INSERT INTO Customers 
(

CustomerName, 
Address, 
City, 
PostalCode,
Country
)

VALUES
 
(

'Hekkan Burger',
'Gateveien 15',
'Sandnes',
'4306',
'Norway'
)
;

NULL empty value

A field with a NULL value is a field with no value. If a field in a table is optional, a new record can be inserted or a record updated without adding a value to the field. Then, the field will be saved as a NULL value.
Note : A NULL value is not the same as a zero value or a field that contains spaces. Fields with NULL values ​​are fields that are left blank during record creation!
How to test for NULL values?
Comparison operators such as =, <, or <> cannot be used to test for NULL values. We will have to use the IS NULL and IS NOT NULL operators instead.
IS NULL syntax

SELECT column_names
FROM table_name
WHERE column_name IS NULL;

IS NOT NULL syntax

SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;

Let's take the "Customers" table as an example:
insert image description here

The IS NULL operator
lists all customers with a NULL value in the "Address" field:

SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;

Tip : Always use IS NULL to find NULL values.
IS NOT NULL operator
The IS NOT NULL operator is used to test for non-null values ​​(NOT NULL values).
Lists all customers that have a value in the "Address" field:

SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;

Exercise:
Select all records PostalCode from Customers where the column is empty.

SELECT * FROM Customers
WHERE PostalCode IS NULL;

UPDATE update statement

The UPDATE statement is used to modify existing records in a table.
UPDATE syntax:

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Note: Be careful when updating records in the table! Note the clause UPDATE in the WHERE statement. The WHERE clause specifies which records should be updated. If the WHERE clause is omitted, all records in the table will be updated!
Let's take the "Customers" table as an example:
insert image description here
Update the table
Update the user name and city data with CustomerID = 1

UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;

After the update will be as follows:
insert image description here
Update multiple records
The WHERE clause determines how many records will be updated.
Update the ContactName to "Juan" for all records whose country is "Mexico":

UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';

After the update it will become:
insert image description here
Update Warning!
Be careful when updating records. If the WHERE clause is omitted, all records will be updated!
E.g:

UPDATE Customers
SET ContactName='Juan';

This will result in the following result:
insert image description here
Exercise:
Update the Customers column of all records in the table City.

UPDATE Customers
SET City = 'Oslo';

DELETE delete statement

The DELETE statement is used to delete existing records in the table.
delete syntax

DELETE FROM table_name WHERE condition;

Note: Be careful when deleting records in the table! Note the DELETE clause in the WHERE statement. The WHERE clause specifies which records should be deleted. If you omit the WHERE clause, all records in the table will be deleted!
Hahahaha, let's take the "Customers" table as an example as follows:
insert image description here
delete example
Delete the customer "Alfreds Futterkiste" from the "Customers" table:

DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

So it becomes this:
insert image description here
delete all records
You can delete all rows in a table without deleting the table. This means that the table structure, properties and indexes will remain the same

DELETE FROM table_name;

For example: delete all rows in the "Customers" table, but not delete the table:

DELETE FROM Customers;

Exercise : Delete all records with a Country value of "Norway" from the Customers table.

DELETE FROM Customers
WHERE Country = 'Norway';

TOP, LIMIT, FETCH FIRST, or ROWNUM limit clause

SELECT TOP clause
The SELECT TOP clause is used to specify the number of records to return. The SELECT TOP clause is useful on large tables with thousands of records. Returning a large number of records can affect performance.
Note: Not all database systems support the SELECT TOP clause. MySQL supports the LIMIT clause to select a limited number of records, while Oracle uses the FETCH FIRST n ROWSONLYROWNUM
Server/MS access syntax:

SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;

MySQL syntax:

SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;

Oracle 12 syntax:

SELECT column_name(s)
FROM table_name
ORDER BY column_name(s)
FETCH FIRST number ROWS ONLY;

For example, the following
insert image description here
example of TOP, LIMIT and FETCH FIRST
from the "Customers" table selects the first three records from the "Customers" table (for SQL Server/MS Access):

SELECT TOP 3 * FROM Customers;

Equivalent example for MySQL:

SELECT * FROM Customers
LIMIT 3;

Equivalent example for Oracle:

SELECT * FROM Customers
FETCH FIRST 3 ROWS ONLY;

TOP PERCENT Example
to select the top 50% of records from the "Customers" table (for SQL Server/MS Access):

SELECT TOP 50 PERCENT * FROM Customers;

Equivalent example for Oracle:

SELECT * FROM Customers
FETCH FIRST 50 PERCENT ROWS ONLY;

Add a WHERE clause
to select the first three records from the "Customers" table, where the country is "Germany" (for SQL Server/MS Access):

SELECT TOP 3 * FROM Customers
WHERE Country='Germany';

Equivalent example for MySQL

SELECT * FROM Customers
WHERE Country='Germany'
LIMIT 3;

Equivalent example for Oracle:

SELECT * FROM Customers
WHERE Country='Germany'
FETCH FIRST 3 ROWS ONLY;

MIN() and MAX() functions to find the maximum and minimum values

The MIN() function returns the minimum value of the selected column. The MAX() function returns the maximum value of the selected column.
MIN() syntax

SELECT MIN(column_name)
FROM table_name
WHERE condition;

MAX() syntax

SELECT MAX(column_name)
FROM table_name
WHERE condition;

Now we change to a new table Product as follows:
insert image description here
MIN() Example
Find the price of the cheapest product:

SELECT MIN(Price) AS SmallestPrice
FROM Products;

The display looks like this:
insert image description here
MAX() Example
Find the price of the most expensive product:

SELECT MAX(Price) AS LargestPrice
FROM Products;

Returns as follows:
insert image description here
Exercise:
Use the MIN function to select the record with the minimum value of the Price column.

SELECT  MIN(Price) FROM  Products;

COUNT(), AVG() and SUM() functions

The COUNT() function returns the number of rows that match the specified criteria.
COUNT() syntax

SELECT COUNT(column_name)
FROM table_name
WHERE condition;

The AVG() function returns the average of a numeric column.
AVG() syntax

SELECT AVG(column_name)
FROM table_name
WHERE condition;

The SUM() function returns the sum of a numeric column.
SUM() syntax

SELECT SUM(column_name)
FROM table_name
WHERE condition;

Let's still use the table product
insert image description here
COUNT() example
to find the number of products:

SELECT COUNT(ProductID)
FROM Products;

Note: NULL values ​​are not counted.
AVG() example
Find the average price of all products:

SELECT AVG(Price)
FROM Products;

Note: NULL values ​​are ignored.
Suppose I now have the "OrderDetails" table as follows:
insert image description here
SUM() Example
Find the sum of the "Quantity" field in the "OrderDetails" table:

SELECT SUM(Quantity)
FROM OrderDetails;

Returns as follows:
insert image description here
Note: NULL values ​​are ignored.
Exercise :
Return the number of records with the Price value set to 18

SELECT COUNT(*) FROM Products
WHERE Price = 18;

LIKE operator

The LIKE operator is used in the WHERE clause to search for the specified pattern in the column. There are two wildcard characters that are often used in conjunction with the LIKE operator: the
percent sign (%) for zero, one or more characters and the
underscore ( ) for one, single character
but note: MS Access uses an asterisk (*) instead of percent signs (%), use question mark (?) instead of underscore (
)
Of course, percent signs and underscores can also be combined!
LIKE syntax

SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;

Tip: You can also combine any number of conditions using AND or OR operators.
Here are some examples showing the different LIKE operators with the "%" and "_" wildcards:
insert image description here
The corresponding meanings are:
Line 1: Match any field starting with a
Line 2: Match any field ending with a
Line 3: Match any field with "or"
Line 4: Find any value that has an "r" in the second position
Line 5: Find any value that starts with "a" and is at least 2 characters long
Line 6 : finds any value that starts with "a" and is at least 3 characters long
Line 7: looks for any value that starts with "a" and ends with "o" For
example, we still have the following Customers table:
insert image description here

LIKE example
To select all customers whose CustomerName starts with "a":

SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';

Select all customers whose CustomerName ends with "a":

SELECT * FROM Customers
WHERE CustomerName LIKE '%a';

Select all customers with an "or" anywhere in CustomerName:

SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';

Select all customers with the second position "r" in CustomerName:

SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';

Select all customers whose CustomerName starts with "a" and is at least 3 characters long:

SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';

Select all customers whose ContactName starts with "a" and ends with "o":

SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';

Select all customers whose CustomerName does not start with "a":

SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';

wildcard *? ! Wait

This is the description of all the wildcard characters in the English document (I really don't want to translate, let's see for yourself)
insert image description here
insert image description here
Suppose we still have the following "Customers" table:
insert image description here
Use the % wildcard
to select all customers whose City starts with "ber":

SELECT * FROM Customers
WHERE City LIKE 'ber%';

Select all customers whose City contains "es":

SELECT * FROM Customers
WHERE City LIKE '%es%';

Returns as follows:
insert image description here
Use the _ wildcard
to select all customers whose City starts with any character followed by "ondon":

SELECT * FROM Customers
WHERE City LIKE '_ondon';

Select all customers whose City starts with "L" followed by any character, "n", any character, "on":

SELECT * FROM Customers
WHERE City LIKE 'L_n_on';

Use the [charlist] wildcard
to select all customers whose City starts with "b", "s" or "p":

SELECT * FROM Customers
WHERE City LIKE '[bsp]%';

Select all customers whose City starts with "a", "b" or "c":

SELECT * FROM Customers
WHERE City LIKE '[a-c]%';

Use the [!charlist] wildcard
to select all customers whose City does not start with "b", "s" or "p":

SELECT * FROM Customers
WHERE City LIKE '[!bsp]%';

or

SELECT * FROM Customers
WHERE City NOT LIKE '[bsp]%';

IN operator

The IN operator allows you to specify multiple values ​​in the WHERE clause.
The IN operation is for multiple shorthand OR conditions.
IN syntax

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);

Let's take the "Customers" table again as an example:
insert image description here
IN operator example
To select all customers located in 'Germany', 'France', 'UK':

SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');

Select not to select all customers located in 'Germany', 'France', 'UK':

SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');

Select all customers from the same country as Suppliers:

SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);

Return as follows
insert image description here

BETWEEN operator

The BETWEEN operator selects a value within a given range. Values ​​can be numbers, text, or dates.
BETWEEN syntax

SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

We use the following product table:
insert image description here
between example
to select all products with a price between 10 and 20:

SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;

To display products outside the scope of the previous example, use NOT BETWEEN:

SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;

Between the numbers
Select all products with a price between 10 and 20. Also; do not display products with CategoryID 1,2 or 3:

SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);

Between text values
​​statement selects all products with ProductName between Carnarvon Tigers and Mozzarella di Giovanni

SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;

Select all products with product names between Carnarvon Tigers and Chef Anton's Cajun Seasoning:

SELECT * FROM Products
WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's Cajun Seasoning"
ORDER BY ProductName;

NOT BETWEEN text value
Select all products whose ProductName is not between Carnarvon Tigers and Mozzarella di Giovanni:

SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;

Let's now assume we have the following "Orders" table:
insert image description here
Example
Between Dates Select all orders with an OrderDate between '01-July-1996' and '31-July-1996'

SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/01/1996# AND #07/31/1996#;

or use:

SELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';

AS alias usage

Alias ​​column syntax

SELECT column_name AS alias_name
FROM table_name;

Alias ​​Table Syntax

SELECT column_name(s)
FROM table_name AS alias_name;

Now let's still assume that we have the custorm table as follows:
insert image description here
there is also an alias example for the oeder table
insert image description here
column
Create two aliases, one for the CustomerID column and the other for the CustomerName column:

SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;

Create two aliases, one for the CustomerName column and one for the ContactName column. Note: Double quotes or square brackets are required if the alias contains spaces:

SELECT CustomerName AS Customer, ContactName AS [Contact Person]
FROM Customers;

Create an alias called "Address" that combines the four columns (Address, PostalCode, City, and Country):

SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' + Country AS Address
FROM Customers;

Note: To make the above SQL statement work in MySQL, use the following command:

SELECT CustomerName, CONCAT(Address,', ',PostalCode,', ',City,', ',Country) AS Address
FROM Customers;

Example of table alias
Select all orders from customer with CustomerID=4 (Around the Horn). We use the "Customers" and "Orders" tables, giving them table aliases "c" and "o" respectively (here we use aliases to shorten the SQL)

SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName='Around the Horn' AND c.CustomerID=o.CustomerID;

The following SQL statement is the same as above, but without the alias:

SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName='Around the Horn' AND Customers.CustomerID=Orders.CustomerID;

Aliases are useful when:
1. A query involves multiple tables
2. A query involves multiple tables
3. Functions used in the query
4. Column names are large or not very readable
5. Two or more columns combine it all toghther

JOIN connection

The JOIN clause is used to join rows from two or more tables based on the related columns between them.
Suppose we now have the "Orders" table as follows
insert image description here
and also the table "Customers" as follows:
insert image description here
Note that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the "Customers" table. The relationship between the above two tables is the "CustomerID" column.
Example
Use INNER JOIN to select records with matching values ​​in both tables:

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

Returns the following
insert image description here
different types of SQL JOIN
insert image description here

INNER JOIN inner join keyword

The INNER JOIN keyword selects records that have matching values ​​in both tables.
grammar:

SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;

Draw a picture to understand:
insert image description here
Suppose we still have the order table
insert image description here
customer table
insert image description here
INNER JOIN Example
Select all orders that contain customer information:

SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

Return
insert image description here
JOIN three tables
to select all orders with customer and shipper information

SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
FROM ((Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);

Return as follows
insert image description here

LEFT JOIN left join keyword

The LEFT JOIN keyword returns all records in the left table (table1), and matching records in the right table (table2). If there is no match, the result is 0 records to the right.
Left join syntax

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;

You can understand it with a picture.
insert image description here
We still use the customer table:
insert image description here
order table
insert image description here
LEFT JOIN example
Select all customers, and any orders they may have:

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;

Return as follows
insert image description here

RIGHT JOIN right join keyword

grammar

SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

Now we
insert image description here
use the order table as follows
insert image description here
. There is also an employee table that
insert image description here
returns all employees, and any orders they may have placed:

SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;

FULL OUTER JOIN keyword

FULL OUTER JOIN is the same as FULL JOIN.
The syntax is:

SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;

You can understand it with a picture.
insert image description here
We assume that we still use the customer table
insert image description here
and an order table
insert image description here
to select all customers and all orders:

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

Return as follows
insert image description here

Self Join keyword

grammar

SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;

Let's assume there is a custormer table
insert image description here
matching customers from the same city:

SELECT A.CustomerName AS CustomerName1, B.CustomerName AS CustomerName2, A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City
ORDER BY A.City;

Return as follows
insert image description here

GROUP BY statement

The GROUP BY statement groups rows with the same value into summary rows, such as "Find the number of customers in each country".
The GROUP BY statement is typically used with aggregate functions ( COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result set by one or more columns.
grammar:

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

Suppose we still have the customer table
insert image description here
listing the number of customers in each country:

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;

The number of customers in each country is listed, sorted from highest to lowest:

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;

HAVING clause

grammar:

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);

Suppose there is still a custorm table below that
insert image description here
lists the number of customers in each country. Only include countries with more than 5 customers:

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;

The number of customers in each country is listed, sorted from highest to lowest (only countries with more than 5 customers are included):

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;

EXISTS operator

EXISTS operator is used to test if any records exist in the subquery.
The EXISTS operator returns true if the subquery returns one or more records.
grammar

SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);

Suppose we still use the product table supplier
insert image description here
table
insert image description here
For example:
return TRUE and list suppliers whose product price is less than 20:

SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID = Suppliers.supplierID AND Price < 20);

Returns as follows
insert image description here
Returns TRUE and lists suppliers whose product price is equal to 22:

SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID = Suppliers.supplierID AND Price = 22);

returns as:
insert image description here

Notes

Single-line comments start with –.
– and any text between the end of the line will be ignored (not executed).
For example:

--Select all:
SELECT * FROM Customers;

Another example

SELECT * FROM Customers -- WHERE City='Berlin';

Multi-line comments /* and any text between /./ and * /
are ignored.
E.g:

/*Select all the columns
of all the records
in the Customers table:*/
SELECT * FROM Customers;

Another example

/*SELECT * FROM Customers;
SELECT * FROM Products;
SELECT * FROM Orders;
SELECT * FROM Categories;*/
SELECT * FROM Suppliers;

Ignore part of a statement:
e.g.

SELECT CustomerName, /*City,*/ Country FROM Customers;

Another example

SELECT * FROM Customers WHERE (CustomerName LIKE 'L%'
OR CustomerName LIKE 'R%' /*OR CustomerName LIKE 'S%'
OR CustomerName LIKE 'T%'*/ OR CustomerName LIKE 'W%')
AND Country='USA'
ORDER BY CustomerName;

operator

In fact, in this section, I have already demonstrated the previous operators. Say it again.
Arithmetic operators have a
insert image description here
demonstration part ,
such as finding 20+30:

SELECT 30 + 20;

division (returns 3)

SELECT 30 / 10;

Take the remainder (return 2)

SELECT 17 % 5;

Comparison operator
insert image description here
Demonstrate part
Greater than

SELECT * FROM Products
WHERE Price = 18;     

not equal to

SELECT * FROM Products
WHERE Price <> 18;

greater or equal to

SELECT * FROM Products
WHERE Price >= 30;

Guess you like

Origin blog.csdn.net/weixin_46211269/article/details/119814777