请参阅下表。如果数字不是唯一的,我想列出所有带有名称和数字的行

表格1

+------+-------+
|ID    |Name   |
+------+-------+
|1     |A      |
+------+-------+
|2     |A      |
+------+-------+
|3     |A      |
+------+-------+
|4     |B      |
+------+-------+
|5     |B      |
+------+-------+


表2

+------+-------+
|ID    |Number |
+------+-------+
|1     |1234   |
+------+-------+
|2     |123    |
+------+-------+
|3     |1234   |
+------+-------+
|4     |456    |
+------+-------+
|5     |456    |
+------+-------+


我尝试了以下查询。这将列出所有具有不区分编号的名称,但只会给我第一行。

SELECT table1.Name, table2.Number
FROM table1, table2
WHERE table1.ID = table2.ID
GROUP BY table1.Name having count(distinct table2.Number) > 1;

+------+-------+
|Name  |Number |
+------+-------+
|A     |1234   |
+------+-------+


我想要的是如果同一名称上有不同的数字,则列出所有行。

+------+-------+
|Name  |Number |
+------+-------+
|A     |1234   |
+------+-------+
|A     |123    |
+------+-------+
|A     |1234   |
+------+-------+

最佳答案

您可以通过将两个表连接在一起并完成对子查询的第二次连接来完成所需的工作,该子查询标识具有不同的数字计数(大于1)的名称。

SELECT t1.Name, t2.Number
FROM table2 t2
INNER JOIN table1 t1
    ON t2.ID = t1.ID
INNER JOIN
(
    SELECT t1.Name
    FROM table2 t2
    INNER JOIN table1 t1
        ON t2.ID = t1.ID
    GROUP BY t1.Name
    HAVING COUNT(DISTINCT t2.Number) > 1    -- # distinct numbers > 1
) t3
    ON t1.Name = t3.Name                    -- restrict to matching names only


演示在这里:

SQLFiddle

关于mysql - MySQL根据id选择所有具有不同值的行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42004569/

10-11 04:08