gpt4 book ai didi

mysql - 查询以返回所有行的所有重复项

转载 作者:行者123 更新时间:2023-11-29 02:58:10 28 4
gpt4 key购买 nike

我想返回表中的每一行,以及在特定列中具有重复值的每一行的 ID。我可以很容易地获得所有重复项,但我需要返回更多数据

示例数据:

--------------------------------
| Firstname | Lastname | ID |
--------------------------------
| John | Smith | 1 |
--------------------------------
| Jane | Smith | 2 |
--------------------------------
| Bill | Smith | 3 |
--------------------------------

如果我匹配姓氏,我想返回

ID    Firstname   Lastname   dup_Fname  dup_Lname dup_id
1 John Smith Jane Smith 2
1 John Smith Bill Smith 3
2 Jane Smith John Smith 1
2 Jane Smith Bill Smith 3
3 Bill Smith John Smith 1
2 Bill Smith Jane Smith 2

我真的只需要返回 ID,但为了清楚起见在示例中包含了名称

最佳答案

您可以通过使用不同的别名将表与自身连接起来来做到这一点:

SELECT T1.ID, T1.FirstName, T1.LastName,
T2.FirstName as dup_FName, T2.LastName as dup_LName, T2.ID as dup_id
FROM TableName T1, TableName T2
WHERE T1.ID <> T2.ID
ORDER BY T1.ID,T2.ID

结果:

ID  FIRSTNAME   LASTNAME    DUP_FNAME   DUP_LNAME   DUP_ID
1 John Smith Jane Smith 2
1 John Smith Bill Smith 3
2 Jane Smith John Smith 1
2 Jane Smith Bill Smith 3
3 Bill Smith John Smith 1
3 Bill Smith Jane Smith 2

SQL Fiddle 中查看结果.

关于mysql - 查询以返回所有行的所有重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27878271/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com