简体   繁体   English

Mysql连接表,但仅包含特定行的结果

[英]Mysql join tables but only results with a specific row

three tables: Customers (id_cus, cli_name, ...) Products (id_pro, pro_name, ...) Orders (id_cus, id_pro) 三个表:客户(id_cus,cli_name,...)产品(id_pro,pro_name,...)订单(id_cus,id_pro)

Table Orders is relation between Customers and Products. 表订单是客户与产品之间的关系。

Question is: How to get Customers (id_cus) who choose only specific product. 问题是: 如何获得仅选择特定产品的客户(id_cus)。

Example: Product A (id_pro= 100) and want all Clients customers who only bought this Product A , not Product A and Product B . 示例: 产品A (id_pro = 100),并希望仅购买产品A 而不是产品A和产品B的所有客户客户。 Only Product A (id_pro = 100). 仅产品A(id_pro = 100)。

SELECT `id_cus` from `Orders` where `id_pro=100;

This give me all Customers who have ever bought Product A (and maybe Product B, C too). 这给了我所有曾经购买过产品A(也许也购买过产品B,C)的客户。

Sorry, no idea. 对不起,不知道

Take a look to EXISTS 看看到EXISTS

Simply: 只是:

SELECT o.id_cus
FROM orders o
WHERE o.id_pro = 100
    AND NOT EXISTS (SELECT * from orders o2 where o2.id_cus = o.id_cus AND o2.id_pro != 100)

You can use aggregation for this: 您可以为此使用聚合:

select o.id_cus
from orders o
group by o.id_cus
having min(o.id_pro) = max(o.id_pro) and min(o.id_pro) = 100;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM