📅  最后修改于: 2023-12-03 14:47:38.533000             🧑  作者: Mango
SQL 连接用于将两个或多个表中的数据连接起来,从而进行更复杂的查询。常用的连接方式包括 INNER JOIN、LEFT JOIN、RIGHT JOIN 和 OUTER JOIN。
子查询则是在一个查询中嵌套另一个查询,以实现更复杂的查询需求。子查询可以用于 SELECT、FROM、WHERE 和 HAVING 子句中。
INNER JOIN 返回只有在两个表中都存在的记录,基于两个表中的共同数据列进行匹配。语法如下:
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
示例:
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID = Customers.CustomerID;
LEFT JOIN 返回左表中所有记录,以及右表中与左表匹配的记录。如果右表中没有与左表匹配的记录,则返回 NULL。语法如下:
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
示例:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
与 LEFT JOIN 相反,RIGHT JOIN 返回右表中的所有记录以及左表与右表匹配的记录。如果左表中没有与右表匹配的记录,则返回 NULL。语法如下:
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
示例:
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees
ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderDate;
OUTER JOIN 用于将左表和右表中的所有记录都包含在结果集中,并在没有匹配的记录处添加 NULL 值。语法如下:
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name;
示例:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
可以在 SELECT 子句中嵌套查询,从而返回一个值,比如最大值、最小值等等。语法如下:
SELECT column_name(s)
FROM table_name
WHERE column_name operator
(SELECT column_name
FROM table_name
WHERE condition);
示例:
SELECT CustomerName, OrderPrice
FROM Customers
WHERE OrderPrice > (SELECT AVG(OrderPrice) FROM Orders);
在 FROM 子句中使用子查询,可以从一个表中选择数据并根据所选的数据从另一个表中获取数据。语法如下:
SELECT *
FROM (SELECT column_name(s)
FROM table_name
WHERE condition) AS alias_name
JOIN table_name2
ON alias_name.column_name = table_name2.column_name;
示例:
SELECT *
FROM (SELECT Customers.CustomerID, Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID) AS CustomerOrders
JOIN OrderDetails
ON CustomerOrders.OrderID = OrderDetails.OrderID;
在 WHERE 子句中使用子查询,可以根据另一个表中的值过滤出需要的数据。语法如下:
SELECT column_name(s)
FROM table_name
WHERE column_name operator
(SELECT column_name
FROM table_name
WHERE condition);
示例:
SELECT *
FROM Customers
WHERE CustomerID IN (SELECT CustomerID FROM Orders);
在 HAVING 子句中使用子查询,可以根据另一个表中的聚合函数结果过滤出需要的数据。语法如下:
SELECT column_name(s)
FROM table_name
GROUP BY column_name(s)
HAVING aggregate_function(column_name) operator value;
示例:
SELECT CustomerID, AVG(OrderPrice) AS AvgPrice
FROM Orders
GROUP BY CustomerID
HAVING AVG(OrderPrice) > (SELECT AVG(OrderPrice) FROM Orders);
以上就是 SQL 连接与子查询的介绍,它们都是 SQL 查询语言的重要部分,可以让我们更加灵活地查询数据库中的数据。