多行SQL Where子句

时间:2010-08-15 17:12:00

标签: 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

我需要获得的是具有特定PositionId和Qty的所有行。类似的东西:

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

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

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

然后,UnionId of 5仍然会被退回。

5 个答案:

答案 0 :(得分: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>

答案 1 :(得分:2)

试试这个:

   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)

这在语义上更接近于你的意图

答案 2 :(得分:1)

这应该返回5:

SELECT DISTINCT lineups1.leagueid
FROM lineups AS lineups1 INNER JOIN lineups AS LINEUPS2 
ON lineups1.LeagueId=lineups2.LeagueId
WHERE lineups1.PositionId=1 AND lineups2.Qty = 1 
  AND  lineups2.PositionId=3 AND lineups2.Qty = 2

由于您只能选择单行,因此如果要考虑多个行,则必须加入另一个表。在这种情况下,你是“自我加入”阵容的表格,根据另一行的条件从一行中检索价值(当然,因为它们是相同的,所以你选择的联盟并不重要。)

更新您当然可以将其扩展到

SELECT lineups1.ID, ..., lineupts2.ID, ...

检索要检索的字段。

答案 3 :(得分:1)

SELECT       DISTINCT LeagueId /*to display non-repeating record*/
FROM         Lineups
WHERE        PositionId in (1,3) AND Qty in (1,2) /*OR*/

第一个声明将返回2个联盟ID为5的记录,但如果您的目的是获得包含这些位置和QTY的联盟ID,请将'AND'替换为'OR',然后它将返回联盟ID 4和5。

答案 4 :(得分:0)

您也可以尝试:

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