ch04: 集合运算

练习题(请给出代码、包含代码及代码执行结果的截图)

4.1

找出 product 和 product2 中售价高于 500 的商品的基本信息。

SELECT *
FROM product
WHERE sals_price > 500
UNION
SELECT *
FROM product2
WHERE sals_price > 500

4.2

借助对称差的实现方式, 求product和product2的交集。

SELECT * 
FROM product
WHERE product_id NOT IN (SELECT product_id FROM product2)

4.3

每类商品中售价最高的商品都在哪些商店有售 ?

SELECT SP.shop_id, SP.shop_name, SP.product_id 
FROM shop_product AS SP
WHERE SP.product_id IN
(SELECT p1.product_id FROM product AS p1
INNER JOIN 
(SELECT product_type, MAX(sale_price) AS max_sale_price
FROM product
GROUP BY product_type) AS p2
ON p1.product_type = p2.product_type
AND p1.sale_price = p2.max_sale_price);

4.4

分别使用内连结和关联子查询每一类商品中售价最高的商品。

  • 内连接
SELECT p1.product_id, p1.product_name, p1.product_type, p1.sale_price, p2.max_sale_price 
FROM product AS p1
INNER JOIN 
	(SELECT product_type, MAX(sale_price) AS max_sale_price
	FROM product
	GROUP BY product_type) AS p2
ON p1.product_type = p2.product_type
AND p1.sale_price = p2.max_sale_price;
  • 关联子查询
SELECT p1.product_id, p1.product_name, p1.product_type, p1.sale_price
FROM product AS p1
WHERE p1.sale_price = (SELECT MAX(sale_price) AS max_sale_price
											 FROM product AS p2
											 WHERE p1.product_type = p2.product_type
											 GROUP BY product_type);

4.5

用关联子查询实现:在 product 表中,取出 product_id, product_name, sale_price, 并按照商品的售价从低到高进行排序、对售价进行累计求和。

SELECT product_id, product_name, sale_price,
	   (SELECT SUM(sale_price) FROM product AS P2
		WHERE P1.sale_price >= P2.sale_price
		AND P1.product_id <= P2.product_id) AS cum_price
FROM product AS P1 
ORDER BY sale_price;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值