如何重写DELETE查询以便限制受影响的行?

时间:2013-01-22 16:59:01

标签: mysql

我知道mysql不允许在多个表删除查询中使用LIMIT。我在网上寻找解决方案,但我不确定如何根据我的需要调整它们。以下是删除内容中不包含的所有内容的查询,以保持表与其他条件一起使用。

DELETE f
    FROM   field_data_body f
           INNER JOIN node n
                   ON f.entity_id = n.nid
           LEFT JOIN content_to_keep k
                  ON n.nid = k.nid
    WHERE  n.type = 'article'
           AND k.nid IS NULL

那么我有什么选择来添加LIMIT参数。

编辑: 感谢您的帮助,但大多数答案都使用where in子句。当我使用它时,我收到一条错误消息“此版本的MySQL尚不支持'LIMIT& IN / ALL / ANY / SOME'子查询'

4 个答案:

答案 0 :(得分:2)

DELETE
FROM   field_data_body
WHERE id in (
    SELECT f.id
    FROM   field_data_body f
           INNER JOIN node n
                   ON f.entity_id = n.nid
           LEFT JOIN content_to_keep k
                  ON n.nid = k.nid
    WHERE  n.type = 'article'
           AND k.nid IS NULL)
LIMIT 10; --or whatever you want

答案 1 :(得分:2)

在代码中选择要删除的行的部分中添加ORDER BYLIMIT,然后将其放在派生表中并连接回要删除的表:

DELETE f_del
FROM field_data_body AS f_del
   JOIN
      ( SELECT f.PK                            --- the Primary Key of the table
        FROM   field_data_body f
               INNER JOIN node n
                       ON f.entity_id = n.nid
               LEFT JOIN content_to_keep k
                      ON n.nid = k.nid
        WHERE  n.type = 'article'
               AND k.nid IS NULL
        ORDER BY some_column
        LIMIT 100
      ) AS tmp
      ON tmp.PK = f_del.PK ; 

答案 2 :(得分:0)

也许是为了让你朝着正确的方向前进:

.... WHERE IN(SELECT ... FROM field_data_body WHERE nid IS NULL)

答案 3 :(得分:0)

From another question I was able to do the following

DELETE f 
FROM   field_data_body f 
WHERE  f.entity_id IN (SELECT * 
                   FROM   (SELECT f.entity_id 
                           FROM   field_data_body f 
                                  INNER JOIN node n 
                                          ON f.entity_id = n.nid 
                                  LEFT JOIN mbrd_delete_nodes_to_keep k 
                                         ON n.nid = k.nid 
                           WHERE  n.type = 'forum' 
                                  AND k.nid IS NULL 
                                  AND f.entity_type = 'node' 
                           LIMIT  1) AS t)