gpt4 book ai didi

mysql - sql自连接表删除重复行

转载 作者:IT老高 更新时间:2023-10-28 23:52:46 24 4
gpt4 key购买 nike

我有下表:

╔════════╦════════════╗
║ USERID ║ LANGUAGEID ║
╠════════╬════════════╣
║ 1 ║ 2 ║
║ 1 ║ 7 ║
║ 1 ║ 8 ║
║ 2 ║ 10 ║
║ 2 ║ 3 ║
╚════════╩════════════╝

现在我想为每个用户创建所有可能的语言对这意味着我希望结果集是:对于用户 1:(2,7), (7,8), (2,8)

对于用户 2:(10,3)

为此,我完成了以下查询:

SELECT a.userId , a.LanguageId, b.LanguageId
FROM knownlanguages a, knownlanguages b
WHERE a.userID=b.userID
AND a.LanguageId<>b.LanguageId

我得到的结果是对于用户 1:(2,7), (7,8), (2,8) , (7,2), (8,7), (8,2)

对于用户 2:(10,3), (3,10)

(10,3) 和 (3,10) 对我来说没有区别

如何删除重复的行?

tnx

最佳答案

使用您的标识符:

SELECT a.userId , a.LanguageId, b.LanguageId
FROM knownlanguages a inner join knownlanguages b
on a.userID=b.userID and a.LanguageId < b.LanguageId

测试:Fot表:

create table t ( u int, l int);

insert into t values
( 1, 2),
( 1, 7),
( 1, 8),
( 2, 10),
( 2, 3);

查询是:

select t1.u, t1.l as l1, t2.l as l2
from t t1 inner join t t2
on t1.u = t2.u and t1.l < t2.l

(Results)

关于mysql - sql自连接表删除重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14304928/

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