如何通过重复键查找唯一行

时间:2019-10-23 12:48:18

标签: mysql sql

我需要找到特定车型的Car和Color唯一的行,这些行具有不止一种颜色。

Car Model   Color
---------------------
Skoda   Fabia   Red
Skoda   Fabia   Blue
Skoda   Fabia   Red
Skoda   Octavia Red

我需要显示如下结果:

Skoda Fabia Red
Skoda Fabia Blue

我不想看到这个:

Skoda Octavia Red

我尝试过这个:

SELECT * 
FROM data 
WHERE Model = 'Fabia' 
GROUP BY (Car, Color) 
HAVING COUNT(*)>1 

但这不起作用。

3 个答案:

答案 0 :(得分:2)

我想你想要

select distinct c.*
from cars c
where model = 'Fabia' and
      exists (select 1
              from cars c2
              where c2.model = c.model and
                    c2.car = c.car and
                    c2.color <> c.color
             );

或者,如果您对一栏中的颜色感到满意,那么

select car, model, group_concat(distinct color)
from cars c2
where model = 'Fabia'
group by car, model
having count(distinct color) > 1;

答案 1 :(得分:0)

尝试一下:

SELECT distinct a.* FROM data as a 
JOIN 
(SELECT Car, Model,count(1)
 FROM data 
 GROUP BY Car, Model 
 HAVING count(1) > 1) as b
ON a.Model=b.Model AND a.Car=b.Car;

答案 2 :(得分:0)

我有解决方法:

SELECT *,group_concat(DISTINCT Color) FROM data WHERE model='Fabia' GROUP BY Car HAVING count(DISTINCT Color)>1