MySQL根据id选择具有非不同值的所有行

时间:2017-02-02 14:19:04

标签: mysql

见下表。如果数字不明显,我想列出名称和编号的所有行

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

2 个答案:

答案 0 :(得分:0)

您可以使用子查询执行此操作:

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

否则您的GROUP BY每个表名只会显示1条记录

答案 1 :(得分:0)

您可以通过将两个表连接在一起并完成对子查询的第二次连接来完成您想要的操作,该子查询识别具有大于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