***11、子查询 ***
-- 查询所有订购了RGAN01商品的用户信息
SELECT cust_id, cust_name, cust_contact
FROM customers
WHERE cust_id IN (SELECT cust_id
FROM orders
WHERE order_num IN (SELECT order_num
FROM orderitems
WHERE prod_id = 'RGAN01'));
-- 作为子查询,SELECT只能查询单列
作为计算字段的子查询
-- 查询每个用户的订单数,其实跟联结查询差不多,下章开始联结查询JOIN
-- "="号右边必须指定表名,左边随意
SELECT cust_name,
cust_state,
(SELECT COUNT(*) FROM orders WHERE cust_id = customers.cust_id AS orders)
FROM customers
ORDER BY cust_name;
12、联结查询
等值联结
SELECT vend_name, prod_name, prod_price
FROM vendors, products
WHERE vendros.vend_id = products.vend_id;
或者使用内联(INNER JOIN)
SELECT vend_name, prod_name, prod_price
FROM vendors INNER JOIN products
On vendors.vend_id = products.vend_id;
-- FROM或者ON后面的东西,无所谓前后
上一章的子查询,用多表联结查询来代替
SELECT orders.order_num, cust_name, cust_contact
FROM customers, orders, orderitems
WHERE prod_id = 'RGAN01'
AND orderitems.order_num = orders.order_num
AND customers.cust_id = orders.cust_id;
INNER JOIN联结多表
SELECT orders.order_num, cust_name, cust_contact
FROM (customers INNER JOIN orders ON orders.cust_id = customers.cust_id)
INNER JOIN orderitems ON orderitems.order_num = orders.order_num
WHERE prod_id = 'RGAN01';
13、高级联结
使用别名
FROM customers AS C, orders AS O -- 表别名只在执行中使用,不会返回显示
自连接(使用同一表的不同别名来区分)
SELECT c1.cust_id, c1.cust_name, c1.cust_contact
FROM customers AS c1, customers AS c2
WHERE c1.cust_name = c2.cust_name AND c2.cust_contact = 'Jim Jones';
-- 查询与'Jim Jones'有相同cust_name的所有人
外联结
区别:查询用户和他的订单号,内联结结果为所有有订单的用户,外联结结果为所有用户,包括那些没有订单的
SELECT customers.cust_id, orders.order_num
FROM customers LEFT OUTER JOIN orders
ON customers.cust_id = orders.cust_id;
-- LEFT表示显示JOIN左边的表的所有行,FULL表示两边两边的全部显示,但MySQL不支持
-- 输出,其中2号用户,没有下过订单
-- +------------+-----------+
-- | cust_id | order_num |
-- +------------+-----------+
-- | 1000000001 | 20005 |
-- | 1000000001 | 20009 |
-- | 1000000002 | NULL |
-- | 1000000003 | 20006 |
-- | 1000000004 | 20007 |
-- | 1000000005 | 20008 |
-- +------------+-----------+
联结与聚集函数
-- 查询每个用户的订单数
SELECT customers.cust_id, COUNT(orders.order_num) AS order_count
FROM customers LEFT OUTER JOIN orders
ON customers.cust_id = orders.cust_idGROUP BY customers.cust_id;
14、组合查询
使用UNION
UNION组合2个或2个以上的SELECT,每个SELECT包含的列、表达式、聚集函数必须相同,顺序可以不同
当使用UNION ALL时,两个查询中的重复行,会重复出现~
SELECT cust_name, cust_contact, cust_email
FROM CustomersWHERE cust_state IN ('IL','IN','MI')
UNION
SELECT cust_name, cust_contact, cust_email
FROM Customers
WHERE cust_name = 'Fun4All'
ORDER BY cust_name;
-- 其实与一个查询,然后WHERE xxx OR xxx一样的效果
-- ORDER BY理所当然,只能放在最后,,
参考:SQL必知必会(第四版)