DELETE + JOIN + ORDER BY + LIMIT =语法错误

时间:2011-07-29 22:19:01

标签: mysql delete-row

放弃ORDER BY + LIMIT JOIN,一切都是桃子。把它们放在一起,我似乎释放了海妖。谁可以解决一些问题?

DELETE table1 AS t1
FROM table1 AS t1 LEFT JOIN table2 AS t2 ON t1.id = t2.id
WHERE t2.field = 'something'
ORDER BY t1.id DESC
LIMIT 5

Delete using aliases

我也尝试过没有别名&放弃WHERE,无济于事。始终是语法错误“near 'ORDER BY...”。

3 个答案:

答案 0 :(得分:10)

来自Mysql文档:DELETE

  

对于多表语法,DELETE从每个tbl_name中删除满足条件的行。 在这种情况下,无法使用ORDER BY和LIMIT

在您的情况下,我认为这有效:

DELETE 
FROM table1
WHERE EXISTS
      ( SELECT t2.id
        FROM table2 AS t2
        WHERE t2.id = table1.id
          AND t2.field = 'something'
      ) 
ORDER BY id DESC
LIMIT 5

答案 1 :(得分:3)

如果您确实需要这样做,可以执行以下操作

DELETE table1 
WHERE id in
      (SELECT t.id
      FROM table1 AS t INNER JOIN table2 AS t2 ON t1.id = t2.id
      WHERE t2.field = 'something' --No point in doing a LEFT JOIN because of this
      ORDER BY t1.id DESC
       LIMIT 5)

答案 2 :(得分:1)

t1未被声明为别名。尝试t到处t1(反之亦然)。