从多个表中删除查询

时间:2013-01-14 15:46:41

标签: php mysql sql sql-delete

我想从这个基于reserveringsnr的查询中删除所有这些结果。

(SELECT DISTINCT res.reserveringsnr, datum, begintijd, eindtijd, aantalpersonen, klantnr, betaald, tafr.tafelnr, menr.reserveringsnr, menr.menunr, menr.uniqueid FROM reserveringen as res
    INNER JOIN menus_regel as menr
    ON res.reserveringsnr = menr.reserveringsnr
    INNER JOIN tafels_regel AS tafr
    ON res.reserveringsnr = tafr.reserveringsnr
    WHERE res.reserveringsnr = '21')

但是这样的事似乎不起作用

DELETE FROM 
(SELECT DISTINCT res.reserveringsnr, datum, begintijd, eindtijd, aantalpersonen, klantnr, betaald, tafr.tafelnr, menr.reserveringsnr, menr.menunr, menr.uniqueid FROM reserveringen as res
    INNER JOIN menus_regel as menr
    ON res.reserveringsnr = menr.reserveringsnr
    INNER JOIN tafels_regel AS tafr
    ON res.reserveringsnr = tafr.reserveringsnr
    WHERE res.reserveringsnr = '21')Delete
WHERE Delete.reserveringsnr = '21'

任何人都可以向我推进正确的方向吗? 提前谢谢!

2 个答案:

答案 0 :(得分:1)

以下查询将仅删除表reserveringen上的所有记录。

DELETE  res
FROM    reserveringen as res
        INNER JOIN menus_regel as menr
            ON res.reserveringsnr = menr.reserveringsnr
        INNER JOIN tafels_regel AS tafr
            ON res.reserveringsnr = tafr.reserveringsnr
WHERE   res.reserveringsnr = '21'

但是如果要删除reserveringsnr匹配的所有表中的记录,则需要在DELETE子句中指定所有表名

DELETE  res, menr, tafr
FROM    reserveringen as res
        INNER JOIN menus_regel as menr
            ON res.reserveringsnr = menr.reserveringsnr
        INNER JOIN tafels_regel AS tafr
            ON res.reserveringsnr = tafr.reserveringsnr
WHERE   res.reserveringsnr = '21'

答案 1 :(得分:1)

如果你必须在一行中完成,那么@ JW的答案看起来是正确的。但是,我更倾向于在单独的行中运行这些以解决性能问题 - 如果每个表中有大量记录,则连接将比单个删除时间更长。

DELETE 
FROM reserveringen  
WHERE reserveringsnr = '21';

DELETE 
FROM menus_regel 
WHERE reserveringsnr = '21';

DELETE 
FROM tafels_regel 
WHERE reserveringsnr = '21'

以下是有关删除的有用链接:

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