我有一张桌子
id = 1
name = 'one'
group = 1
id = 2
name = 'two'
group = 1
id = 3
name = 'three'
group = 2
我必须在一个sql查询中获得所有单身名称,在这种情况下id = 3 和另一个sql所有的名称都是倍数,在这种情况下id = 1和id = 2,因为它们具有相同的组。 我想它应该是选择但不确定的选择。
提前致谢。
答案 0 :(得分:2)
听起来你想要使用类似的东西:
select id
from yourtable
group by `group`
having count(`group`) = 1
然后,如果要返回所有详细信息,则可以将查询扩展为:
select *
from yourtable t1
where id in (select id
from yourtable t2
group by `group`
having count(`group`) = 1)
如果要返回具有相同组的所有行,则可以使用:
select *
from yourtable t1
where `group` in (select `group`
from yourtable t2
group by `group`
having count(`group`) > 1)
然后,如果您想要返回所有内容以及标识它是单个还是多个的标志,那么您可以使用与此类似的内容。您会注意到我添加了一个标志,以显示groups
有一行,然后哪些组有多行:
select *, 'single' Total
from yourtable t1
where `group` in (select `group`
from yourtable t2
group by `group`
having count(`group`) = 1)
union all
select *, 'multiple' Total
from yourtable t1
where `group` in (select `group`
from yourtable t2
group by `group`
having count(`group`) > 1)