题目:
表: Product
+--------------+---------+ | Column Name | Type | +--------------+---------+ | product_id | int | | product_name | varchar | | unit_price | int | +--------------+---------+ product_id 是该表的主键(具有唯一值的列)。 该表的每一行显示每个产品的名称和价格。
表:Sales
+-------------+---------+ | Column Name | Type | +-------------+---------+ | seller_id | int | | product_id | int | | buyer_id | int | | sale_date | date | | quantity | int | | price | int | +------ ------+---------+ 这个表可能有重复的行。 product_id 是 Product 表的外键(reference 列)。 该表的每一行包含关于一个销售的一些信息。
编写解决方案,报告2019年春季
才售出的产品。即仅在2019-01-01
至2019-03-31
(含)之间出售的商品。
解题:
这道题挺简单的。
简单的联表+distinct关键字+not exists 自连接查询。
not exist 即下面的SQL语句加粗的字段,就表示它是连的自己,看同一个product_id ,是否有不在该日期范围内的数据。
select distinct p.product_id,p.product_name from Product p ,Sales s where p.product_id = s.product_id and s.sale_date between
'2019-01-01' and '2019-03-31' and not exists (select * from Sales s2 where s2.sale_date not between '2019-01-01' and '2019-03-31' and s2.product_id = s.product_id )