mysql - 选择两个值相等的几个 id

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

最佳答案

你只需要像这样连接两个表:

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/

相关文章:

Python 列出依赖于 MySQL 用户和连接的函数

mysql - 对两个 case 表达式的乘法求和

php - 将mysql数据插入div

mysql - Sequelize 不支持 MySQL 8 身份验证协议(protocol),我不知道如何更改此协议(protocol)

java - 数据库查询总是返回true?

mysql - 通过外键查找 Max() 值

mysql - 当该表上已有记录时,在表中添加 FK 字段

mysql - 使用 MySQL 选择多个类别中的产品/事件

mysql - Rails 将 mysql tinyint(1) 视为 bool 值 - 但我希望它是一个数字

php 返回 null 而 mysql 返回用户变量的值