MYSQL - 从SELECT中删除

时间:2012-08-22 06:30:40

标签: mysql phpmyadmin

以下查询给出了“#1093 - 您无法在FROM子句中为更新指定目标表'reservation_seats'”错误。

DELETE 
FROM reservation_seats 
WHERE id IN ( SELECT id 
              FROM reservation_seats 
              WHERE reservation_id NOT IN ( SELECT id FROM reservation)
            );

表格结构:

reservation_seats - id,reservation_id,seat_no
reservation       - id,txn_id,name......
reservation table(id) column is used as the foreign in the reservation_seats table.
(reservation.id = reservation_seats.reservation_id )

你能告诉我为什么会这样,以及如何解决它?

由于

2 个答案:

答案 0 :(得分:3)

在MySQL中,您无法从正在选择的表中删除。尝试

DELETE FROM reservation_seats
WHERE id IN ( 
              select * from 
              (
                   SELECT id FROM reservation_seats
                   WHERE reservation_id NOT IN ( SELECT id FROM reservation)
              )
);

无论如何都要欺骗MySQL。顺便说一句,这可以像这样简化

DELETE FROM reservation_seats
WHERE reservation_id NOT IN ( SELECT id FROM reservation)

答案 1 :(得分:1)

您希望删除席位而无需任何预订

DELETE FROM reservation_seats
WHERE  reservation_id NOT IN (SELECT id
                              FROM   reservation);