26

我有下表:

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

4

2 回答 2

32

使用您的标识符:

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

结果

于 2013-01-13T15:41:55.403 回答
4
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
于 2013-01-13T15:37:42.200 回答