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

 ID   PositionId    Qty     LeagueId
 1        1          1         5
 2        3          2         5
 3        8          5         2
 4        1          6         4


我需要获取的是具有特定PositionId和Qty的所有行。就像是:

 SELECT       ID, PositionId, LeagueId, Qty
 FROM         Lineups
 WHERE        (PositionId = 1 AND Qty = 1) AND (PositionId = 3 AND Qty = 2)


我想要得到的是返回的LeagueId 5,因为它同时具有PositionId为1和Qty 1以及PositionId为3和Qty2。我不想使用OR语句,因为如果将WHERE更改为:

 WHERE (PositionId = 1 AND Qty = 1) OR (PositionId = 3 AND Qty = 1)


然后5的LeagueId仍将返回。

最佳答案

试试这个:

   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)


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

08-07 12:48