SELECT cust_name, cust_contact
FROM Customers AS C, Orders AS O, OrderItems AS OI
WHERE C.cust_id = O.cust_id
AND OI.order_num = O.order_num
AND prod_id = 'RGAN01';
表别名只在查询执行中使用。与列别名不一样,表别名不返回到客户端
13.2 使用不同类型的联结
自联结(self-join)、自然联结(natural join)和外联结(outer join)
# 假如要给与 Jim Jones同一公司的所有顾客发送一封信件
SELECT cust_id, cust_name, cust_contact
FROM Customers
WHERE cust_name = (SELECT cust_name
FROM Customers
WHERE cust_contact = 'Jim Jones');
自然联结
SELECT C.*, O.order_num, O.order_date,
OI.prod_id, OI.quantity, OI.item_price
FROM Customers AS C, Orders AS O, OrderItems AS OI
WHERE C.cust_id = O.cust_id
AND OI.order_num = O.order_num
AND prod_id = 'RGAN01';
# 通配符只对第一个表使用。所有其他列明确列出,所以没有重复的列被检索出来
外联结
对每个顾客下的订单进行计数,包括那些至今尚未下订单的顾客
列出所有产品以及订购数量,包括没有人订购的产品
计算平均销售规模,包括那些至今尚未下订单的顾客
在上述例子中,联结包含了那些在相关表中没有关联行的行。这种联结称为外联结
SELECT Customers.cust_id, Orders.order_num
FROM Customers LEFT OUTER JOIN Orders
ON Customers.cust_id = Orders.cust_id;
# 外联结还包括没有关联行的行
# 在使用 OUTER JOIN 语法时,必须使用 RIGHT 或 LEFT 关键字指定包括其所有行的表
13.3 使用带聚集函数的联结
SELECT Customers.cust_id,
COUNT(Orders.order_num) AS num_ord
FROM Customers INNER JOIN Orders
ON Customers.cust_id = Orders.cust_id
GROUP BY Customers.cust_id;
# 这条 SELECT 语句使用 INNER JOIN 将 Customers 和 Orders 表互# 相关联GROUP BY 子句按顾客分组数据,因此,函数调用
# COUNT(Orders.order_num)对每个顾客的订单计数,将它作为 num_ord 返回
SELECT Customers.cust_id,
COUNT(Orders.order_num) AS num_ord
FROM Customers LEFT OUTER JOIN Orders
ON Customers.cust_id = Orders.cust_id
GROUP BY Customers.cust_id;
# 外联结