例如我有这两个表
+----+----+----+----+ +----+----+----+----+
| id | c1 | c2 | c3 | | id | c1 | c2 | c4 |
+----+----+----+----+ +----+----+----+----+
| 10 | 50 | 55 | 20 | | 20 | 50 | 55 | 24 |
+----+----+----+----+ +----+----+----+----+
| 12 | 15 | 10 | 70 | | 26 | 21 | 82 | 11 |
+----+----+----+----+ +----+----+----+----+
| 18 | 15 | 10 | 88 | | 27 | 15 | 10 | 13 |
+----+----+----+----+ +----+----+----+----+
我想得到两个具有相同 c1
和 c2
值的 id,对于上面的例子我必须得到这个输出:
+----+----+
| id | id |
+----+----+
| 10 | 20 |
+----+----+
| 12 | 27 |
+----+----+
| 12 | 18 |
+----+----+
| 18 | 27 |
+----+----+
最佳答案
你只需要像这样连接两个表:
SELECT DISTINCT t1.id as id1, t2.id as id2
FROM table1 AS t1
INNER JOIN table2 AS t2 ON t1.c1 = t2.c1 AND t1.c2 = t2.c2
UNION
SELECT DISTINCT t1.id as id1, t2.id as id2
FROM table1 AS t1
INNER JOIN table1 AS t2 ON t1.c1 = t2.c1 AND t1.c2 = t2.c2
AND t1.id != t2.id
UNION
SELECT DISTINCT t1.id as id1, t2.id as id2
FROM table2 AS t1
INNER JOIN table2 AS t2 ON t1.c1 = t2.c1 AND t1.c2 = t2.c2
AND t1.id != t2.id;
Results :
| id1 | id2 |
|-----|-----|
| 10 | 20 |
| 12 | 27 |
| 18 | 27 |
| 18 | 12 |
| 12 | 18 |
关于mysql - 选择两个值相等的几个 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47969035/