以下代码只是一个简化的描述,由于数据集,查询的结构必须是这样的。
我想找到一个值,该值可以存在于子查询的两列中。
这就是我现在所拥有的:
SELECT * FROM PEOPLE WHERE RELATION = 'child'
and (
'John' IN (SELECT FIRSTNAME FROM PEOPLE WHERE AGE = 20 AND RELATION = 'parent' ) OR
'John' IN (SELECT ALIAS FROM PEOPLE WHERE AGE = 20 AND RELATION = 'parent')
) ;
我发现OR的表现非常糟糕。
我想要达到的目标是:
SELECT * FROM PEOPLE WHERE RELATION = 'child' AND 'John' IN
(SELECT FIRSTNAME, ALIAS FROM PEOPLE WHERE AGE = 20 AND RELATION = 'parent');
此示例中的firstname和别名不一定是相同的值,因此我不能使用:
SELECT * FROM PEOPLE WHERE RELATION = 'child' AND ('John','John') IN
(SELECT FIRSTNAME, ALIAS FROM PEOPLE WHERE AGE = 20 AND RELATION = 'parent');
因为这只会找到FIRSTNAME = ALIAS =' John'。
有没有比现在更好的方法呢?
答案 0 :(得分:2)
可能是这样的吗?
SELECT *
FROM people
WHERE relation = 'child'
AND EXISTS (SELECT 1
FROM people
WHERE age = 20
AND relation = 'parent'
AND ( firstname = 'john'
OR alias = 'john' )) ;