简体   繁体   English

仅选择非唯一的行[MySQL]

[英]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'? 例如,我有以下数据集,如何仅选择“位置”值相同的2行?

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

In this example I would select rows 2 and 4 only. 在此示例中,我将仅选择第2行和第4行。

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. 这将为您提供一组行(4列),其中有重复项。 You will get 1 row for a duplicate, 3 for a triplicate, 6 for a quad, and it increases from that point on. 复制将获得1行,一式三份获得3行,四元组获得6行,并且从该点开始增加。

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: 为了进一步扩展Matt S的答案(正确的答案),您可以使用他的结果并加入原始表以获取确切的行:

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 :) ). 在WHERE子句中使用CTE或EXISTS()函数将使其更易于阅读,但我不知道MySQL在语法上支持什么(我是T-SQL的家伙:))。 This should be ANSI. 这应该是ANSI。

Matt S's answer is the way you would generally get what you're looking for. Matt S的答案是通常可以得到想要的东西的方式。 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. 为了稍微扩展scottE的答案(并且由于我们在谈论MySQL),如果输出令人满意,您也可以使用group_concat()来收集所需的信息。

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

should return you: 应该返回您:

IDs | ID | position 位置
2, 4 | 2,4 | 1 1个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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