如何在sql中用一条语句实现多表级联删除?
你遇到了一个多表级联删除的问题,使用的是如下 sql 语句:
delete dish, dish_flavor, setmeal_dish from dish, dish_flavor, setmeal_dish where dish.id = dish_flavor.id and dish.id = setmeal_dish.id and dish.id in (51, 52);
然而,执行后却发现前两张表中的数据没有被删除,第三张表是空的。问题出在哪里呢?
你的语句本质上与下面的语句等效:
delete dish, dish_flavor, setmeal_dish from dish join dish_flavor on dish.id = dish_flavor.id join setmeal_dish on dish.id = setmeal_dish.id where dish.id in (51, 52);
由于第三张表没有满足条件的数据,不符合内连接的条件,导致没有记录被删除。
要实现即使第三张表没有数据也能删除前两张表中的数据,可以使用左连接:
DELETE dish, dish_flavor, setmeal_dish FROM dish LEFT JOIN dish_flavor ON dish.id = dish_flavor.id LEFT JOIN setmeal_dish ON dish.id = setmeal_dish.id WHERE dish.id IN (51, 52);
这样,即使第三张表为空,前两张表中的数据也会被删除。