我要做的是ORDER BY
两个fieds,usrid
和ctoon_id
,COUNT
每个ctoon_id
usrid
的数量,然后DELETE
来自指定usrid
的X记录,只要ctoon_id
计数大于50。
我确定会有嵌套查询,但我没有足够的SQL使用经验来使其正常工作。有人可以帮忙吗?
答案 0 :(得分:0)
要在ctoon_id计数大于50的情况下删除所有50以上的记录,您可以尝试此查询吗?
先选择,确认
首先,运行SELECT,以确保您正在删除正确的记录并且数据库的语法正确:
SELECT DISTINCT userid, ctoon_id
FROM (
SELECT
@row_number := CASE
WHEN @userid = usrid AND @ctoon_id = ctoon_id THEN @row_number + 1
ELSE 1
END AS rnum,
@userid:=usrid AS usrid,
@ctoon_id:=ctoon_id AS ctoon_id
FROM yourtable
ORDER BY usrid, ctoon_id
) sub
WHERE rnum > 50;
此查询将:
您可以先单独运行子查询以查看受影响的记录。
删除记录
要删除记录,请将此SELECT包装在DELETE查询中。
DELETE FROM yourtable
WHERE (usrid, ctoon_id) IN (
SELECT DISTINCT userid, ctoon_id
FROM (
SELECT
@row_number := CASE
WHEN @userid = usrid AND @ctoon_id = ctoon_id THEN @row_number + 1
ELSE 1
END AS rnum,
@userid:=usrid AS usrid,
@ctoon_id:=ctoon_id AS ctoon_id
FROM yourtable
ORDER BY usrid, ctoon_id
) sub
WHERE rnum > 50
);
希望现在好了。