需要通过值进行GROUP和COUNT记录,然后是qty> X得到DELETED到某个数量

时间:2017-01-24 18:35:32

标签: mysql sql

我要做的是ORDER BY两个fieds,usridctoon_idCOUNT每个ctoon_id usrid的数量,然后DELETE来自指定usrid的X记录,只要ctoon_id计数大于50。

我确定会有嵌套查询,但我没有足够的SQL使用经验来使其正​​常工作。有人可以帮忙吗?

1 个答案:

答案 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;

此查询将:

  1. 运行子查询以查找usrid和ctoon_id值并为其分配rownumber
  2. 选择包含50条以上记录的DISTINCT值。
  3. 您可以先单独运行子查询以查看受影响的记录。

    删除记录

    要删除记录,请将此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
    );
    

    希望现在好了。