我有一个看起来像这样的SQL数据集:
SourceId SomeContent
-------------------
1 aaa
2 bbb
3 ccc
4 ddd
SourceId ConditionType CondidionValue
-------------------------------
1 1 2
1 2 200
2 1 3
2 2 201
3 1 4
我需要选择具有匹配特定键的SourceId, 例如(ConditionType = 1和ConditionValue = 2)和(ConditionType = 2和ConditionValue = 200)应该返回sourceId = 1)。具有指定键的查询只能匹配一个SourceId。
我正试图通过这种方式做到这一点:
SELECT SourceId
FROM ConditionData
where ConditionType = 2 and ConditionValue = 200
and SourceId in(
SELECT SourceId
FROM ConditionData
where (ConditionType = 1 and ConditionValue = 2))
是否有更优雅的查询来获取它?
答案 0 :(得分:1)
您可以使用聚合:
SELECT SourceId
FROM ConditionData
WHERE (ConditionType = 2 and ConditionValue = 200)
OR (ConditionType = 1 and ConditionValue = 2)
GROUP BY SourceId
HAVING COUNT(1) = 2 -- Alternatively: COUNT(1) > 1
答案 1 :(得分:0)
我认为您可以为每种条件使用INNER JOIN
SELECT DISTINCT t1.SourceId
FROM table1 AS t1
INNER JOIN table2 AS condition1 ON t1.SourceId = condition1.SourceId AND condition1.ConditionType = 1 AND condition1.CondidionValue = 2
INNER JOIN table2 AS condition2 ON t1.SourceId = condition2.SourceId AND condition2.ConditionType = 2 AND condition2.CondidionValue = 200