Sqlite

SQLite - 獲取具有任何重複列值的所有其他行

  • July 27, 2019

我有一張使用者表,其中包含有關他們的資訊以及欄位的組合,並且UserName是唯一的(作為一個整體的一行,不僅在一個欄位上)

使用者

+----------+--------+--------+--------+
| UserName | Field1 | Field2 | Field3 |
+----------+--------+--------+--------+
| UserNum1 | AAABBB | CCCDDD | EEEFFF |
| UserNum2 | AAABBB | IIIJJJ | KKKFFF |
| UserNum3 | LLLMMM | CCCDDD | PPPQQQ |
| UserNum4 | RRRSSS | TTTUUU | VVVWWW |
+----------+--------+--------+--------+

給定一個要查找的列值,我必須動態地為所有列找到具有任何相同列值​​的其他使用者。

例如,我只提供了使用者名“UserNum1”作為UserName它應該返回使用者 2 和 3,因為它們Field1 and Field2分別的值。

期望的輸出:

+----------+--------+--------+--------+
| UserName | Field1 | Field2 | Field3 |
+----------+--------+--------+--------+
| UserNum2 | AAABBB | IIIJJJ | KKKFFF | # Field1 has same value on User1 & User2
| UserNum3 | LLLMMM | CCCDDD | PPPQQQ | # Field2 has same value on User1 & User3
+----------+--------+--------+--------+

有沒有辦法在一個查詢中做到這一點?還是我真的必須查詢每一列並在我的後端進行其他處理

僅供參考:最初的問題是,根據類似欄位查找可能的使用者重複帳戶或“alts”

sqlite> select
  ...>    Username,
  ...>    Field1,
  ...>    Field2,
  ...>    Field3,
  ...>    (select u2.Username from User u2 where u2.Username<>u1.Username and u2.Field1=u1.field1)  as F1check,           ...>    (select u2.Username from User u2 where u2.Username<>u1.Username and u2.Field2=u1.field2)  as F2check,           ...>    (select u2.Username from User u2 where u2.Username<>u1.Username and u2.Field3=u1.field3)  as F2check
  ...> from User u1;
Username    field1      field2      field3      F1check     F2check     F2check
----------  ----------  ----------  ----------  ----------  ----------  ----------
UserNum1    AAABBB      CCCDDD      EEEFFF      UserNum2    UserNum3
UserNum2    AAABBB      IIIJJJ      KKKFFF      UserNum1
UserNum3    LLLMMM      CCCDDD      PPPQQQ                  UserNum1
UserNum4    RRRSSS      TTTUUU      VVVWWW
sqlite>

注意:如果您有更多的雙倍值,則只顯示第一個,即如果您也有此記錄:

insert into User values ('Usernum5','AAABBB','XXXYYY','XXXYYY')

然後輸出將顯示:

sqlite> select
  ...>    Username,
  ...>    Field1,
  ...>    Field2,
  ...>    Field3,
  ...>    (select u2.Username from User u2 where u2.Username<>u1.Username and u2.Field1=u1.field1)  as F1check,           ...>    (select u2.Username from User u2 where u2.Username<>u1.Username and u2.Field2=u1.field2)  as F2check,           ...>    (select u2.Username from User u2 where u2.Username<>u1.Username and u2.Field3=u1.field3)  as F2check
  ...> from User u1;
Username    field1      field2      field3      F1check     F2check     F2check
----------  ----------  ----------  ----------  ----------  ----------  ----------
UserNum1    AAABBB      CCCDDD      EEEFFF      UserNum2    UserNum3
UserNum2    AAABBB      IIIJJJ      KKKFFF      UserNum1
UserNum3    LLLMMM      CCCDDD      PPPQQQ                  UserNum1
UserNum4    RRRSSS      TTTUUU      VVVWWW
Usernum5    AAABBB      XXXYYY      XXXYYY      UserNum1
sqlite>

您在哪裡看到(在“Usernum5”行)僅引用 Usernum1,而不是 Usernum2。

引用自:https://dba.stackexchange.com/questions/243943