检索mysql中另一个结果集的所有行匹配的行

时间:2017-11-03 10:14:33

标签: mysql sql database

以下是我的申请表

  

产品展示(产品(PK),名称,价格)

     

客户(CUSTOMER_ID(PK),CUSTOMER_NAME,地址)

     

购买(CUSTOMER_ID(FK),PRODUCT_ID(FK),数量);

select count(product_id),customer_id from purchases 
where product_id in ( 
                     select product_id from product where price >200) 
group by customer_id

我能够在这里进行上述查询检索每个客户的产品数量。我甚至试过了下面的一个

select sub.customer_id from (select count(product_id) as prod_count,
customer_id from purchases where product_id in 
                                         ( select product_id from product where price >200) 
group by customer_id) as sub 
having sub.prod_count=(select count(product_id) from product where price>200); 

现在我如何找到购买价格超过200的所有产品的客户。

3 个答案:

答案 0 :(得分:0)

SELECT  DISTINCT customer_id
FROM (
       SELECT   PUR.customer_id, PUR.product_id
                FROM (SELECT product_id FROM Product WHERE price > 200 ) Pro_above_200 PRO
                INNER JOIN Purchases PUR
                ON PUR.product_id = PRO.product_id ) T 
GROUP BY customer_id, product_id
HAVING COUNT(1) = (SELECT COUNT(1) FROM  Product WHERE price > 200 )

答案 1 :(得分:0)

试试这个:

SELECT distinct customer_id  from purchase
where customer_id not in 
(
 select customer_id 
 from(
   select purchases.customer_id , 
       case when Product.proce>200 then 1 else 0 end as price_gt_twh

   from purchases 
   left join Producton purchases.product_id =Product.product_id 
)data
WHERE price_gt_twh=0
)customers

答案 2 :(得分:-1)

Select * from customer join select * from product where product.price > 200.  

我假设您的产品表中有价格列

您需要的是加入声明