MySQL在另一列中选择一组具有多个变体的列

时间:2016-12-16 03:57:31

标签: mysql

表格如下:

id group name
1  1     A
2  1     A
3  2     A
4  2     B
5  3     A

我想在同一组中选择具有多个不同名称的行。结果应如下:

id group name
3  2     A
4  2     B

知道怎么做到这一点?

2 个答案:

答案 0 :(得分:0)

您可以通过聚合获取组:

select group
from t
group by group
having min(name) <> max(name);

您可以使用joininexists获取原始行:

select t.*
from t
where t.group in (select group
                  from t
                  group by group
                  having min(name) <> max(name)
                 );

注意:group是一个糟糕的列名,因为它是一个SQL关键字和一个MySQL保留字。

答案 1 :(得分:0)

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

SELECT t1.id, t1.group, t1.name
FROM mytable AS t1
WHERE EXISTS (
    SELECT * FROM mytable t2 
    WHERE t2.group=t1.group AND t2.name <> t1.name
);

或者您可以通过计算组中的不同名称来实现:

SELECT t1.id, t1.group, t2.name
FROM mytable AS t1
INNER JOIN (
    SELECT t2.group FROM mytable AS t2
    GROUP BY t2.group HAVING COUNT(DISTINCT t2.name) > 1
) AS t2 USING (group);