简体   繁体   中英

Select only the rows that aren't unique [MySQL]

I'm trying to make a query that will check for duplicates, and if I find duplicates I want to be able to update those accordingly. For example, I have the following data set, how do I only select the 2 rows that have the same value for 'position'?

 ID position 1 0 2 1 3 2 4 1 5 3 

In this example I would select rows 2 and 4 only.

SELECT t.position, 
    count(t.*) AS count 
FROM table t
GROUP BY position 
HAVING count(position) > 1

Should return an a list of positions and their repetition counts.

Edit: Neglected to alias my table

If you want to see the rows that have duplicate positions try:

SELECT t1.ID,
    t1.position,
    t2.ID,
    t2.position
FROM table t1
INNER JOIN table t2
    ON t1.ID < t2.ID
    AND t1.position = t2.position

This will give you a set of rows (4 columns) where there are duplicates. You will get 1 row for a duplicate, 3 for a triplicate, 6 for a quad, and it increases from that point on.

To expand a little on Matt S's answer (which is right on), you could use his results and join back to the original table to get the exact rows:

select
    id
    ,position
from table t
    join (
        select t1.position
        from table t1
        group by t1.position
        having count(*) > 1
    ) list
    on t.position = list.position

Using a CTE or an EXISTS() function in a WHERE clause would make this a little easier to read, but I don't know what MySQL syntactically supports (I'm a T-SQL guy :) ). This should be ANSI.

Matt S's answer is the way you would generally get what you're looking for. To expand slightly on scottE's answer (and since we're talking MySQL), you could also use group_concat() to pull together the info you're looking for, if the output is pleasing.

SELECT group_concat(ID) as 'IDs', position
FROM table
GROUP BY position
HAVING count(position) > 1

should return you:

IDs | position
2, 4 | 1

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