sql自联接表删除重复的行

时间:2013-01-13 15:30:54

标签: mysql sql

我有下表:

╔════════╦════════════╗
║ 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

2 个答案:

答案 0 :(得分:22)

使用您的标识符:

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

测试:对于表:

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

答案 1 :(得分:3)

SELECT  userId,
        LEAST(LANG_ID1, LANG_ID2) ID1,
        GREATEST(LANG_ID1, LANG_ID2) ID2
FROM
    (
      SELECT a.userId, 
             a.LanguageId LANG_ID1, 
             b.LanguageId LANG_ID2
      FROM   knownlanguages a, knownlanguages b  
      WHERE  a.userID=b.userID  AND 
             a.LanguageId <> b.LanguageId
    ) s
GROUP BY userId, ID1, ID2

输出,

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

或简单地说,

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