How to select rows where multiple joined table values meet selection criteria?

前端 未结 3 1492
我寻月下人不归
我寻月下人不归 2021-01-20 17:58

Given the following sample table schema

Customer Table

CustID
1
2
3

Invoice Table

CustID InvoiceID

1       10
1            


        
相关标签:
3条回答
  • 2021-01-20 18:27

    Use:

      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
    

    The key thing is that the counting of i.invoiceid needs to equal the number of arguments in the IN clause.

    The use of COUNT(DISTINCT i.invoiceid) is in case there isn't a unique constraint on the combination of custid and invoiceid -- if there's no chance of duplicates you can omit the DISTINCT from the query:

      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
    
    0 讨论(0)
  • 2021-01-20 18:39
    select CustID
        from InvoiceTable
        where InvoiceID in (10,20)
        group by CustID
        having COUNT(distinct InvoiceID) = 2
    
    0 讨论(0)
  • 2021-01-20 18:42

    The Group By answers will work unless it is possible for there to be multiples of CustID/InvoiceId in the Invoice table. Then you might get some unexpected results. I like the answer below a little better because it mirrors more closely the logic as you are describing it.

    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)
    
    0 讨论(0)
提交回复
热议问题