知识学习(随记)
- 从表的加减法中间的练习题可以看出,union不仅可以用于对两个表取并,也可以用于对同一个表的不同条件的筛选取并。
- 也可以用union测试数据的兼容性。
- mysql即使到了8.0,也还是有好些不支持的运算。
练习题
4.1 找出 product 和 product2 中售价高于 500 的商品的基本信息
sql
SELECT *
FROM Product
WHERE sale_price > 500
UNION ALL
SELECT *
FROM Product2
WHERE sale_price > 500;
4.2 借助对称差的实现方式, 求product和product2的交集
sql
SELECT *
FROM
(SELECT *
FROM product
UNION
SELECT *
From product2) u
WHERE product_id NOT IN
(SELECT product_id
FROM product
WHERE product_id NOT IN (SELECT product_id FROM product2)
UNION
SELECT product_id
FROM product2
WHERE product_id NOT IN (SELECT product_id FROM product));
4.3 每类商品中售价最高的商品都在哪些商店有售 ?
sql
SELECT sp.shop_id, sp.shop_name, sp.product_id, p.product_type
FROM shopproduct sp
INNER JOIN product p
ON sp.product_id = p.product_id
WHERE sp.product_id IN
(SELECT product_id
FROM product p1
INNER JOIN (SELECT product_type, MAX(sale_price) as max_price
FROM product
GROUP BY product_type) p2
ON p1.product_type = p2.product_type AND p1.sale_price=p2.max_price);
4.4 分别使用内连结和关联子查询每一类商品中售价最高的商品
内连结查询
sql
SELECT product_name, product_type, sale_price
FROM product AS P1
WHERE sale_price = (SELECT MAX(sale_price)
FROM product AS P2
WHERE P1.product_type = P2.product_type)
关键子查询
sql
SELECT P1.product_id, P1.product_name, P1.product_type, P1.sale_price, P1.max_price
FROM product AS P1
INNER JOIN (SELECT product_type, MAX(sale_price) AS max_price
FROM product
GROUP BY product_type) AS P2 ON P1.product_type = P2.product_type
WHERE P1.sale_price = P2.max_price
4.5 用关联子查询实现:在 product 表中,取出 product_id, product_name, sale_price, 并按照商品的售价从低到高进行排序、对售价进行累计求和。
sql
SELECT product_id, product_name, sale_price,(SELECT SUM(sale_price)
FROM product p2 WHERE p2.sale_price <= p1.sale_price) AS cumulative_sum
FROM product p1
ORDER BY sale_price;