2017-06-05 83 views
0

考慮到這種表:Mysql的選擇X重複的N,省略1重複

+-----+--------+ 
| id | value | 
+-----+--------+ 
| 1 | 22 | 
+-----+--------+ 
| 2 | 12 | 
+-----+--------+ 
| 3 | 22 | 
+-----+--------+ 
| 4 | 22 | 
+-----+ -------+ 

我可以選擇所有其中列value被複制像這樣:

select value from table having count(value) > 1 ; 

這將輸出的Ids 1 ,3和4.

我試圖做的是選擇重複的地方,但留下1(一)重複未選中,所以上面只會輸出Ids 3和4(或1和3等...重複省略並不重要,只是它是。

我該如何做到這一點?

這個問題不是

Using LIMIT within GROUP BY to get N results per group?

回答

0

重複你可以使用一個aggregatio功能過濾器ID和選擇所有其他的值

select * from table 
    where (value, id) not in (
     select value, max(id) 
     from table 
     group by value 
     having count(value) > 1 
) 
    ; 
0

你可以這樣做:

select * 
from test t1 
where exists (select 1 
       from test t2 
       where t2.value = t1.value 
       having count(value)>1) 
limit 2 

OR:

select t1.* 
    from test t1 inner join 
     (select value from test t2 having count(value)>1) t2 
     on t1.value = t2.value 
limit 2;