我有以下表格,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)
答案 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
)
答案 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;