2013-02-21 38 views
0

多單行我有一個表獲得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,因爲它們具有相同的組。 我想它應該是選擇在選擇,但不確定。

在此先感謝。

回答

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

+0

好,它的工作,但其只獲得了單打,如何得到id 1和2?不管怎樣,謝謝。 – Centurion 2013-02-21 14:22:43

+0

@Centurion。 。 。你將'having'從'= 1'改爲'in(1,2)'。 – 2013-02-21 14:25:29

+0

@戈登·利諾夫,這個想法是讓這些有組超過了兩個ID,我希望你明白 – Centurion 2013-02-21 14:30:43