0

我有一张桌子

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,因为它们具有相同的组。我想它应该是选择中的选择,但不确定。

提前致谢。

4

1 回答 1

2

听起来您想使用类似的东西:

select id
from yourtable
group by `group`
having count(`group`) = 1

请参阅SQL Fiddle with Demo

然后,如果您想返回所有详细信息,则可以将查询扩展为:

select *
from yourtable t1
where id in (select id
            from yourtable t2
            group by `group`
            having count(`group`) = 1)

请参阅SQL Fiddle with Demo

如果要返回具有相同组的所有行,则可以使用:

select *
from yourtable t1
where `group` in (select `group`
                  from yourtable t2
                  group by `group`
                  having count(`group`) > 1)

请参阅带有演示的 SQL Fiddle

然后,如果您想返回所有内容和一个标识它是单个还是多个的标志,那么您可以使用与此类似的东西。你会注意到我包含了一个标志来显示哪些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)

请参阅带有演示的 SQL Fiddle

于 2013-02-21T14:11:36.640 回答