简体   繁体   中英

get multiple and single rows in mysql

I have a table

id = 1
name = 'one'
group = 1

id = 2
name = 'two'
group = 1

id = 3
name = 'three'
group = 2

and i have to get in one sql query all names which are singles, in this case id = 3 and another sql all names which are multiples, in this case id=1 and id=2, since they have the same group. I suppose it should be a select in select but not sure.

Thanks in advance.

It sounds like you want to use something similar to this:

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

See SQL Fiddle with Demo .

Then if you want to return all details, then you can expand the query to:

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

See SQL Fiddle with Demo .

If you want to return all rows that have the same group, then you can use:

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

See SQL Fiddle with Demo

Then if you want to return everything and a flag that identifies if it is a single or multiple, then you can use something similar to this. You will notice that I included a flag to show what groups have one row and then what groups have more than one row:

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)

See SQL Fiddle with Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM