如何使用JOIN从同一个表中选择在某些列中只具有唯一值的行?

时间:2017-05-25 15:42:11

标签: mysql sql join

我有三栏的苹果桌

Id Color Price

此表中的数据

+----+-----------+------+
| Id | Color     | Price| 
+----+-----------+------+
| 1  | Red       | 5    | 
| 2  | Red       | 1    |  
| 3  | Green     | 3    |
| 4  | Orange    | 4    |
+----+-----------+------+-

在结果表格中,我想看到:

+----+-----------+------+
| Id | Color     | Price| 
+----+-----------+------+
| 3  | Green     | 3    |
| 4  | Orange    | 4    |
+----+-----------+------+

如何在没有子查询的情况下使用连接执行此操作?

此时我的查询只选择了红苹果:

select *
from apples as a1
left join apples as a2
on a1.Id != a2.Id
where a1.Color = a2.Color;

6 个答案:

答案 0 :(得分:1)

稍微修改了你的查询。查询只有1个left join而不是subquerieshaving子句,并且可以在大多数数据库中使用

检查一下。

select distinct a1.*
from apples as a1
inner join apples as a2
on a1.Color < a2.Color;

OR

select distinct a1.*
from apples as a1
inner join apples as a2
on a1.Id > a2.Id
where a1.Color != a2.Color;

希望这会有所帮助: - )

答案 1 :(得分:0)

你不需要join ......这样的事情应该有效:

SELECT *
FROM apples
GROUP BY Color
HAVING COUNT(*)=1

I made a fiddle

答案 2 :(得分:0)

内部查询:当您将它们组合在一起时,选择只有一个出现的所有颜色。外部查询:选择所有苹果,其中颜色是内部查询选择的颜色之一。

select * from Apples 
    where Color in (
        select Color from Apples group by Color having count(*)=1
    )

答案 3 :(得分:0)

或使用ONLY联接:

select Apples.* 
    from Apples
    inner join 
    (
        select Color from Apples group by Color having count(*)=1
    ) colors on colors.Color=Apples.Color

答案 4 :(得分:0)

受印度的启发。火箭:

select A.Id, A.Color, A.Price
     from Apples A
     left join Apples A2 on A2.Color= A.Color and A2.Id<>A.Id
     where A2.Id is null
     group by A.Id, A.Color, A.Price

答案 5 :(得分:0)

此查询适用于sqlfiddle和MySql 5.7。

首先,我连接表以选择具有重复颜色的行。然后我加入结果表并从表中删除重复项。

select a1.*
from apples as a1
left join apples as a2
on (a1.Id <> a2.Id and a1.Color = a2.Color)
left join apples a3
on (a2.Color is null and a1.Id = a3.Id)
where a3.Color is not null;

http://sqlfiddle.com/#!9/23df971/1