从多行中选择ID,其中列值满足一个条件,但不满足另一个条件

时间:2018-07-30 15:45:35

标签: sql

您好,我遇到以下问题。

我有一个与此sql fiddle中的表类似的表 该表定义了一种关系,并且包含其他两个表的ID

示例值

| FirstID  | SecondID  | 
|  1       |     1     |
|  1       |     2     |
|  1       |     3     |
|  2       |     1     |
|  2       |     2     |
|  2       |     3     |
|  2       |     4     |
|  2       |     5     |
|  3       |     1     |
|  3       |     2     |
|  3       |     3     |

我要选择满足以下条件的所有FirstID。 它们对应的SecondID在1-3范围内,而不在4-5范围内

例如,在这种情况下,我们需要FirstID 1和3。

我尝试了以下查询

SELECT FirstID from table 
WHERE SecondID IN (1,2,3) AND SecondID NOT IN (4,5)

SELECT  FirstID,SecondID
FROM(
   SELECT FirstID, SecondID
   FROM  table
   WHERE  SecondID in (1,2,3,4,5) ) 
WHERE SecondID NOT IN (4,5)

但是我没有得到我想要的正确结果。

获取我想要的数据的正确查询是什么?

4 个答案:

答案 0 :(得分:2)

SELECT FirstID
FROM table
WHERE SecondId in (1,2,3) --Included values
AND FirstID NOT IN (SELECT FirstID FROM test
                    WHERE SecondId IN (4,5)) --Excluded values

答案 1 :(得分:1)

min()max()怎么样:

select firstid
from t
group by firstid
having min(secondId) between 1 and 3 and
       max(secondid) between 1 and 3;

假设1为最小值,则可以简化为:

having max(secondid) <= 3;

对于任意范围,您可以使用sum(case)

having sum(case when secondId between 1 and 3 then 1 else 0 end) > 0 and
       sum(case when secondId between 4 and 5 then 1 else 0 end) = 0;

答案 2 :(得分:1)

我认为Gonzalo Lorieto可能已经很好地回答了这个问题,但是根据您数据的大小,SELECT子句中的WHERE语句可能会变得很慢,下面可能是明显更快(尽管目前尚不清楚是否值得降低可读性...)

SELECT inrange.FirstId FROM 
t inrange
LEFT OUTER JOIN 
(SELECT FirstID FROM t
WHERE SEcondId IN (4,5)) outrange
ON inrange.firstID = outrange.firstId
WHERE SecondID IN (1,2,3)
AND outrange.firstId IS NULL
GROUP BY inrange.FirstId

答案 3 :(得分:0)

您将要使用EXISTS子句排除具有无效SecondID的FirstID。这是一个例子:

SELECT FirstID from test Has123
WHERE SecondID IN (1,2,3)
AND NOT EXISTS (
  SELECT 1 FROM test Not45 
  WHERE Has123.FirstID = Not45.FirstID 
  AND Not45.SecondID IN (4,5)
)
GROUP BY FirstID

SqlFiddle