给出以下样本表模式
客户表
CustID
1
2
3
发票表
CustID InvoiceID
1 10
1 20
1 30
2 10
2 20
3 10
3 30
目标是选择InvoiceID值为10和20(非OR)的所有客户。因此,在此示例中,将返回客户w / CustID = 1和2。
您将如何构造SELECT语句?
答案 0 :(得分:6)
使用:
SELECT c.custid
FROM CUSTOMER c
JOIN INVOICE i ON i.custid = c.custid
WHERE i.invoiceid IN (10, 20)
GROUP BY c.custid
HAVING COUNT(DISTINCT i.invoiceid) = 2
关键是i.invoiceid
的计数需要等于IN
子句中的参数数量。
如果对custid和invoiceid的组合没有唯一约束,则使用COUNT(DISTINCT i.invoiceid)
- 如果没有重复的可能性,则可以省略查询中的DISTINCT:
SELECT c.custid
FROM CUSTOMER c
JOIN INVOICE i ON i.custid = c.custid
WHERE i.invoiceid IN (10, 20)
GROUP BY c.custid
HAVING COUNT(i.invoiceid) = 2
答案 1 :(得分:1)
除非可能在Invoice表中有多个CustID / InvoiceId,否则Group By答案将起作用。然后你可能得到一些意想不到的结果我更喜欢下面的答案,因为它更能反映出你所描述的逻辑。
Select CustID
From Customer
Where
Exists (Select 1 from Invoice Where CustID=Customer.CustID and InvoiceID=10)
and
Exists (Select 1 from Invoice Where CustID=Customer.CustID and InvoiceID=20)
答案 2 :(得分:0)
select CustID
from InvoiceTable
where InvoiceID in (10,20)
group by CustID
having COUNT(distinct InvoiceID) = 2