DELETE记录除了每个用户的最大类别ID - MySQL

时间:2014-11-11 06:20:50

标签: mysql

我有以下表格,SQLFiddle

对于每个用户,我想删除除最大类别ID以外的所有记录。

所以我的表应该看起来像你可以看到SQLFiddle中的第二个查询结果

我尝试过但没有用。

DELETE FROM tbl_categories
    WHERE category_id NOT IN (SELECT * 
                    FROM (SELECT MAX(n.category_id)
                            FROM tbl_categories n
                        GROUP BY n.user_id) x)

2 个答案:

答案 0 :(得分:1)

您的查询几乎是正确的但您没有在WHERE子句中使用user_id,如下所示:

DELETE FROM tbl_categories
WHERE (user_id, category_id) NOT IN (
  SELECT * FROM (
    SELECT t1.user_id, MAX(t1.category_id) as category_id
    FROM tbl_categories t1
    GROUP BY t1.user_id
  ) t
)

工作小提琴:http://sqlfiddle.com/#!2/22a7d/1

答案 1 :(得分:1)

您也可以这样写:

delete
t1.*
from
tbl_categories t1
left join tbl_categories t2 on t1.category_id < t2.category_id 
                            and t1.user_id = t2.user_id
where t2.category_id is not null;