在两个值中选择一对id等于

时间:2017-12-25 13:21:43

标签: mysql

我得到了这两张表,例如

+----+----+----+----+   +----+----+----+----+
| 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 |
+----+----+----+----+   +----+----+----+----+

我希望使用相同的c1c2值来获取其中的两个id,对于上面的示例,我必须得到此输出:

+----+----+
| id | id |
+----+----+
| 10 | 20 |
+----+----+
| 12 | 27 |
+----+----+
| 12 | 18 |
+----+----+
| 18 | 27 |
+----+----+

2 个答案:

答案 0 :(得分:0)

你只需加入这两个表:

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 |

答案 1 :(得分:0)

试试这个:

SELECT DISTINCT T1.ID AS ID1 ,T2.ID AS ID2 FROM TABLE_1 T1,TABLE_2 T2
WHERE T1.C1 = T2.C1 AND
T1.C2 = T2.C2 
UNION 
SELECT ID1,ID2 FROM (
    SELECT  T1.ID AS ID1 , T2.ID 
    AS ID2 FROM TABLE_1 T1,  TABLE_1 T2
    WHERE T1.C1 = T2.C1 AND
    T1.C2 = T2.C2 AND T1.ID! = T2.ID)
WHERE (ID1,ID2) IN ((ID1,ID2),(ID2,ID1)) AND (ID2,ID1)IN ((ID1,ID2),
(ID2,ID1)) AND ROWNUM = 1;

结果:

| id1 | id2 |
|-----|-----|
|  10 |  20 |
|  12 |  27 |
|  18 |  12 |
|  18 |  27 |