簡體   English   中英

在mysql中獲取多行和單行

[英]get multiple and single rows in mysql

我有一張桌子

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,因為它們具有相同的組。 我想它應該是選擇但不確定的選擇。

提前致謝。

聽起來你想要使用類似的東西:

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 with Demo

然后,如果您想要返回所有內容以及標識它是單個還是多個的標志,那么您可以使用與此類似的內容。 您會注意到我包含一個標志,以顯示哪些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 with Demo

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM