SQLite检查子查询是否与其他子查询给出相同的答案

时间:2014-06-20 11:43:19

标签: sql sqlite

我需要像这样构建查询:

SELECT * FROM table1 AS t1 WHERE (
    (SELECT column2 FROM table1 WHERE column1=t1.column1)!=(SELECT column2 FROM table1 WHERE column1=1)
)

但问题是SQLite只检查子查询的第一个结果。

我的意思是,如果SELECT column2 FROM table1 WHERE column1=t1.column1给出以下结果:(1,2,3)SELECT column2 FROM table1 WHERE column1=1给出(1,2,3,4),SQLite将只检查1!=1,而不是(1,2,3)!=(1,2,3,4)

我需要过滤prevoius两个查询只提供相同行的行(即第一行(1,2,3)和第二行(1,2,3)

我的表格的例子:

id | column1 | column2 | ...
1  |       1 |       1 | ...
2  |       1 |       2 | ...
3  |       1 |       3 | ...
4  |       2 |       1 | ...
5  |       2 |       2 | ...
6  |       2 |       3 | ...
7  |       2 |       4 | ...
8  |       3 |       1 | ...
9  |       3 |       2 | ...
10 |       3 |       3 | ...

我需要从id=4id=7获取行,因为它有7 | 2 | 4 | ...行(对于一个column1值,与column1中的column2值不同)

1 个答案:

答案 0 :(得分:2)

您可以尝试compound select statements:相互减去子查询并检查是否有任何行:

SELECT *
FROM table1 AS t1
WHERE EXISTS (SELECT column2 FROM table1 WHERE column1=t1.column1
              EXCEPT
              SELECT column2 FROM table1 WHERE column1=1)
   OR EXISTS (SELECT column2 FROM table1 WHERE column1=1
              EXCEPT
              SELECT column2 FROM table1 WHERE column1=t1.column1)

或者,对单个行执行类似的操作:如果某个行在另一个子查询中没有对应的子查询,则子查询是不同的:

SELECT *
FROM table1 AS t1
WHERE EXISTS (SELECT column2
              FROM table1 AS t2
              WHERE column1 = t1.column1
                AND NOT EXISTS (SELECT 1
                                FROM table1 AS t3
                                WHERE column2 = t2.column2
                                  AND column1 = 1))
   OR EXISTS (SELECT column2
              FROM table1 AS t2
              WHERE column1 = 1
                AND NOT EXISTS (SELECT 1
                                FROM table1 AS t3
                                WHERE column2 = t2.column2
                                  AND column1 = t1.column1))

(如果你有必要的索引,第二个查询可能会更有效。)