我有一个表instructors
,其中包含以下结构/数据:
-----------------
|id | name |
-----------------
|1 | saad |
|2 | imran |
-----------------
我想使用同一个表进行连接而不返回重复的结果。
如果我进行简单连接,查询将返回4行[saad, saad], [saad, imran], [imran, imran], [imran, saad]
。
如果我添加一个where子句,它将返回2行[saad, imran], [imran, saad]
。
但是,我只想返回1行(即如果已经返回[saad, imran]
,则查询不应返回[imran, saad]
)。
到目前为止,这是我的查询:
SELECT DISTINCT
i1.name AS name1,
i2.name AS name2
FROM
instructors i1, instructors i2
WHERE
i1.name != i2.name
ORDER BY
name1, name2
答案 0 :(得分:2)
尝试:
SELECT DISTINCT
i1.name AS name1,
i2.name AS name2
FROM
instructors i1, instructors i2
WHERE
i1.name > i2.name
ORDER BY
name1, name2
答案 1 :(得分:2)
试试这个:
SELECT DISTINCT
i1.name AS name1,
i2.name AS name2
FROM
instructors i1, instructors i2
WHERE
i1.id < i2.id
ORDER BY
name1, name2