我希望购买产品X和Y和Z的customerid来自以下架构:
销售(customerid,productName, rid );
我可以做交集:
select customerid from sales where productName='X'
INTERSECT
select customerid from sales where productName='X'
INTERSTECT
select customerid from sales where productName='Z'
这是我能做的最好的吗?
答案 0 :(得分:6)
不确定这是否适用于postgresql,但请尝试:
select customerid
from sales
where productName in ('X', 'Y', 'Z')
group by customerid
having count(distinct productName) = 3
答案 1 :(得分:2)
您还可以从销售中选择3次:
select s1.customerID
from sales s1, sales s2, sales s3
where s1.productName = 'X'
and S2.productName = 'Y'
and S3.productName = 'Z'
and (S1.customerID = S2.customerID
and s2.customerID = s3.customerID);
或使用正确的连接语法重写(虽然可能不是100%......)
select s1.customerID
from sales s1
inner join sales S2
on s1.customerId = S2.customerID
inner join sales S3
on s2.customerID = S3.customerId
where s1.productName = 'X'
and S2.productName = 'Y'
and S3.productName = 'Z';