您好,我遇到以下问题。
我有一个与此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)
但是我没有得到我想要的正确结果。
获取我想要的数据的正确查询是什么?
答案 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)