SQL - 删除表X中的所有重复条目

时间:2017-05-22 11:49:06

标签: mysql sql

我尝试从表fe_users获取冗余的所有UID列表,然后运行我的DELETE命令删除它们。

e.g。我有这张桌子(fe_users):

uid | pid | username
--------------
1   | 100 |  hans
2   | 100 |  karl
3   | 100 |  franz
4   | 100 |  karl
5   | 100 |  hans

这就是我选择所有重复的方式:

SELECT * FROM fe_users
WHERE uid NOT IN (
    SELECT uid  
    FROM fe_users
    WHERE pid=100
    GROUP BY username
    HAVING COUNT(username) > 1
)
AND username IN (
    SELECT username 
    FROM fe_users
    WHERE pid=100
    GROUP BY username
    HAVING COUNT(username) > 1
)

返回:

uid | pid | username
--------------------
5   | 100 |  hans
4   | 100 |  karl

现在我必须删除它们。

尝试#1:

提示:刚刚使用SELECT从上面的DELETE替换了DELETE * FROM fe_users WHERE uid NOT IN ( SELECT uid FROM fe_users WHERE pid=100 GROUP BY username HAVING COUNT(username) > 1 ) AND username IN ( SELECT username FROM fe_users WHERE pid=100 GROUP BY username HAVING COUNT(username) > 1 )

DELETE FROM fe_users
WHERE uid NOT IN (
    SELECT uid (
        SELECT uid
        FROM fe_users
        WHERE pid=100
        GROUP BY username
        HAVING COUNT(username) > 1
        )
    ) AS uid
AND username IN (
    SELECT username (
        SELECT username 
        FROM fe_users
        WHERE pid=100
        GROUP BY username
        HAVING COUNT(username) > 1
        )
    ) AS username;

响应:

  

您无法指定目标表' fe_users'用于FROM子句中的更新

尝试#2

所以我尝试再使用一个选择,如this answer中建议的那样。

{{1}}

回复:

  

语法错误附近' SELECT uid FROM fe_users WHERE pid = 0 GROUP BY   usernam'在第4行

我不知道如何做到这一点,我想知道MySQL开发人员通过实施这种无意义的限制来思考什么。

我是否必须使用PHP删除它?

2 个答案:

答案 0 :(得分:3)

您的查询似乎比必要的更复杂。我会去:

delete u
    from fe_users u join
         fe_users u2
         on u.pid = u2.pid and u.username = u2.username and
            u2.uid > u.uid
    where u.pid = 100;

这将删除具有相同pidusername的行且uid更大的所有行。您可以通过将delete u更改为select u.*来获取列表。

答案 1 :(得分:0)

我的第二次尝试包含语法错误,因为错误输出已声明。 我错过了FROM,还有其他一些错误。这是有效的查询:

const quadWidth = Math.PI / 2;     // area of effect PI/2 is 90 degree
const steps = radius / quadWidth; // number steps around the circle matches 1 pixel per step, 
const noiseAmpMax = 5;         // in pixels
const noiseWaveMoveSpeed = 2;  // speed of waves on circle in radians per second
const noiseWaveFreq = 16;      // how many waves per 360 deg

我希望MySQL开发人员能够解决这个问题,这样我们就不需要添加不必要的SELECTS了。