MySQL | You can't specify target table 'a' for update in FROM clause

馋奶兔 提交于 2019-12-01 11:33:48

问题


DELETE FROM table_a WHERE id IN(
    SELECT table_a.id AS id FROM table_a, table_b 
    WHERE table_a.object_id = 1 AND table_a.code = 'code' 
        AND table_a.code = table_b.code 
        AND table_b.id = table_a.b_id 
        AND table_b.table = 'testTable')

This is a (somewhat simplified) query I want MySQL to execute. I read on other pages of stackoverflow that this wasn't supported and that it's solvable by using JOINS. How could this be 'transcribed' to a query using JOINS? I find it hard to do so, because I've never tried creating DELETE queries with more than one table.


回答1:


You can't delete from a table and reference the same table in a subquery — just a limitation of MySQL. Something like the following should work:

DELETE FROM table_a 
USING table_a
INNER JOIN table_b
    ON table_a.code = table_b.code
    AND table_b.id = table_a.b_id
    AND table_b.table = 'testTable'
WHERE table_a.object_id = 1 
    AND table_a.code = 'code' 

The important part is USING. If you just join the two tables, you'll delete records from both. USING tells MySQL to use these tables for processing, but only delete from the tables in the FROM clause.

http://dev.mysql.com/doc/refman/5.0/en/delete.html




回答2:


This is a common MySQL issue, use a temporary table between the select and update/delete:

DELETE FROM table_a WHERE id IN 
   (select id from 
       (SELECT table_a.id AS id FROM table_a, table_b 
        WHERE table_a.object_id = 1 
        AND table_a.code = 'code' 
        AND table_a.code = table_b.code 
        AND table_b.id = table_a.b_id 
        AND table_b.table = 'testTable')
    ) tempTable



回答3:


There are two (slightly different) syntaxes for deleting from mutliple tables. Here's the one without USING:

DELETE a
FROM 
      table_a AS a 
  INNER JOIN 
      table_b AS b
    ON  b.code = a.code
    AND b.id   = a.b_id   
WHERE 
      a.object_id = 1 
  AND a.code = 'code' 
  AND b.`table` = 'testTable'   --- Do you actually have a column named "table"?



回答4:


My Way ... If you could use that!

DELETE FROM table_a WHERE id IN(SELECT id FROM(SELECT id FROM table_a WHERE userid=99 GROUP BY mobile HAVING COUNT(mobile) > 1) as t2)


来源:https://stackoverflow.com/questions/9285143/mysql-you-cant-specify-target-table-a-for-update-in-from-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!