LEFT JOIN 左连接 关键字
LEFT JOIN关键字返回左表 (table1) 中的所有记录,以及右表 (table2) 中的匹配记录。如果没有匹配项,则结果是右侧的 0 条记录。
左连接语法
SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;
来个图就懂了
我们还是用customer表:
order表
LEFT JOIN 示例
选择所有客户,以及他们可能拥有的任何订单:
SELECT Customers.CustomerName, Orders.OrderID FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID ORDER BY Customers.CustomerName;
返回如下
RIGHT JOIN右连接 关键字
语法
SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name;
上图就懂了
现在我们用到order表如下
还有个employee表
返回所有员工,以及他们可能下过的任何订单:
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName FROM Orders RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID ORDER BY Orders.OrderID;
FULL OUTER JOIN 关键字
FULL OUTER JOIN和 FULL JOIN是一样的。
语法为:
SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name = table2.column_name WHERE condition;
来个图就懂了
我们假设还是以customer表
还有个order表
选择所有客户和所有订单:
SELECT Customers.CustomerName, Orders.OrderID FROM Customers FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName;
返回如下
Self Join自连接 关键字
语法
SELECT column_name(s) FROM table1 T1, table1 T2 WHERE condition;
我们假设有custormer表
匹配来自同一城市的客户:
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;
返回如下
GROUP BY语句
该GROUP BY语句将具有相同值的行分组为汇总行,例如“查找每个国家/地区的客户数量”。
该GROUP BY语句通常与聚合函数 ( COUNT(), MAX(), MIN(), SUM(), AVG()) 一起使用, 以按一列或多列对结果集进行分组。
语法:
SELECT column_name(s) FROM table_name WHERE condition GROUP BY column_name(s) ORDER BY column_name(s);
假设我们还是有customer这个表
列出了每个国家/地区的客户数量:
SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country;
列出了每个国家的客户数量,从高到低排序:
SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country ORDER BY COUNT(CustomerID) DESC;