首页 > 解决方案 > SQL Query 查找一张表中行的差异

问题描述

假设我有下表:

ID | CMP1 | CMP2 | CMP3 | FK1
------------------------------
1  |   x  |   x  |   x  | 1
2  |   y  |   y  |   y  | 1
3  |   z  |   z  |   z  | 1
------------------------------
4  |   a  |   a  |   a  | 2
5  |   a  |   a  |   a  | 2
6  |   c  |   c  |   c  | 2
------------------------------
7  |   s  |   u  |   v  | 3
8  |   s  |   u  |   i  | 3
9  |   s  |   u  |   z  | 3

现在我必须编写一个查询,返回 FK1 引用但在 CMP1-3 中具有不同值的所有 ID。

例子:

我知道我必须自行加入表格,但我无法比较按 FK1 分组的值 - 请帮助!

谢谢

标签: sqlsqliteforeign-keysself-join

解决方案


您似乎想要 (cmp1, cmp2,​​ cmp3, fk1) 的值是唯一的行。您可以使用窗口功能:

select t.*
from (select t.*,
             count(*) over (partition by cmp1, cmp2, cmp3, fk1) as cnt
      from t
     ) t
where cnt = 1;

另一种方法使用not exists

select t.*
from t
where not exists (select 1
                  from t t2
                  where t2.fk1 = t.fk1 and
                        t2.cmp1 = t.cmp1 and
                        t2.cmp2 = t.cmp2 and
                        t2.cmp3 = t.cmp3 and
                        t2.id <> t.id
                 );

也就是说,没有其他行具有相同的(fk1, cmp1, cmp2, cmp3)组合 - 和不同的id.


推荐阅读