我有两个表,一个名称为nametable
:
id | name
---------
1 | alice
2 | bob
3 | charlie
第二个包含相关数据的datatable
:
id | data
------------
1 | chicken
2 | fish
2 | chicken
3 | spaghetti
现在我想在两个nametable
:
name1 | name2 | data
--------------------
alice | bob | chicken
现在我有了这个:
SELECT nt0.name, nt1.name, nt0.data
FROM nametable AS nt0
INNER JOIN datatable AS dt0
ON nt0.id = dt0.id
LEFT JOIN nametable AS nt1
INNER JOIN datatable AS dt1
ON nt1.id = dt1.id
WHERE dt0.data = dt1.data AND nt0.name < nt1.name;
但它不起作用。我想JOIN
是原因,但我不知道怎么做。
答案 0 :(得分:1)
您可以在派生表上进行自联接:
SELECT
t1.name, t2.name, t1.data
FROM (
SELECT n.id, n.name, d.data
FROM nametable n
INNER JOIN datatable d
ON d.id = n.id
) t1
INNER JOIN (
SELECT n.id, n.name, d.data
FROM nametable n
INNER JOIN datatable d
ON d.id = n.id
)t2
ON t2.data = t1.data
AND t2.id > t1.id