多行SQL Where子句

Kri*_*s B 2 sql where-clause

这可能是一个简单的SQL语句,但是我已经有一段时间了,因为我已经完成了SQL并且我遇到了问题.我有这个表设计:

 ID   PositionId    Qty     LeagueId
 1        1          1         5
 2        3          2         5
 3        8          5         2
 4        1          6         4
Run Code Online (Sandbox Code Playgroud)

我需要得到的是具有特定PositionId和Qty的所有行.就像是:

 SELECT       ID, PositionId, LeagueId, Qty
 FROM         Lineups
 WHERE        (PositionId = 1 AND Qty = 1) AND (PositionId = 3 AND Qty = 2)
Run Code Online (Sandbox Code Playgroud)

我想要获得的是LeagueId 5返回,因为它的PositionId为1,数量为1,PositionId为3和数量2.我不想使用OR语句,因为如果我将WHERE更改为:

 WHERE (PositionId = 1 AND Qty = 1) OR (PositionId = 3 AND Qty = 1)
Run Code Online (Sandbox Code Playgroud)

那么LeagueId of 5仍然会被退回.

Wil*_*l A 6

执行此操作的一般方法是:

 SELECT       LeagueId
 FROM         Lineups
 WHERE        (PositionId = 1 AND Qty = 1) OR (PositionId = 3 AND Qty = 2) OR ...
 GROUP BY     LeagueId
 HAVING COUNT(*) = <number of OR'ed together clauses>
Run Code Online (Sandbox Code Playgroud)


Cha*_*ana 3

尝试这个:

   Select Distinct LeagueId
   From LineUps L
   Where Exists (Select * From LineUps
                 Where LeagueId = L.LeagueId
                    And PositionId = 1 
                    And Qty = 1)
     And Exists (Select * From LineUps
                 Where LeagueId = L.LeagueId
                    And PositionId = 3 
                    And Qty = 2)
Run Code Online (Sandbox Code Playgroud)

这在语义上更接近地代表了您的意图