在一个查询中删除多个表中的行
在一个查询中从多个表中删除行的正确方法是什么?
我之所以问这个问题是因为我正在使用 PHP 来做这件事。如果我使用多个查询一次从每个表中删除一个,PHP 必须多次访问数据库。如果我使用这种方法会对性能产生影响吗?
我知道 ON DELETE CASCADE 选项,但这并不适用于每个存储引擎。另外,在某些情况下,当我删除父记录时,我可能不想删除子表中的所有记录。
What is the proper way to delete rows from several tables in one query?
The reason I ask is because I am doing this with PHP. If I use multiple queries to delete from each table one at a time, PHP has to make multiple trips to the database. Will there be any effect on performance if I used this method?
I am aware of the ON DELETE CASCADE
option, but this does not work on every storage engine. Also, there may be situations where I do not want to remove all of the records from the child tables when I delete the parent record.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
与 DELETE 查询一样:要非常小心
更多详细信息:http:// dev.mysql.com/doc/refman/5.5/en/delete.html
As usual with DELETE queries: be very careful
More details here: http://dev.mysql.com/doc/refman/5.5/en/delete.html
如果您不知道这个问题的答案,那么您不应该尝试为您的应用程序支持大量 RDMS。说白了。 CASCADE 选项在每个重要的关系数据库中都可用。另外,您应该考虑如何存储分层数据、删除子记录。
例如,如果您在使用嵌套集模型时尝试删除“文件夹”中的所有“文件”,那么只需从
id > 的文件中删除即可。 :lft 和 id < :rgt
但是,在任何情况下,您仍然可以通过使用 JOIN 删除从多个表中删除。然而,很多 RDMS 都不支持这一点,因此,如果您担心使用级联,那么即使您使用 DBAL,您也永远无法在每个数据库上使用连接删除。
答案
If you don't know the answer to this question, then you shouldn't be trying to support numerous RDMS's for your application. To put bluntly. The CASCADE option is available in like every relational db that matters. Also, you should consider looking at how to store hierarchical data, to delete child records.
For example, if you were trying to delete all "files" in a "folder" when using Nested Set Model, it would simply be a matter of
DELETE from files where id > :lft and id < :rgt
But, in any case, you can still delete from multiple tables, by using JOIN deletes. However, this is not support by a lot of RDMS, so if you are worried about using cascade, then you are never going to be able to use join deletes accross every database, even if you use a DBAL.
The Answer
我也曾经面临过类似的问题。我的解决方案是编写自己的最小递归查询。只需一个查询,它就会为您完成剩下的工作。其流程如下:
//main 函数
//删除函数..也可以使用工厂函数进行设置,但有 4 个不重要的原因
就是
全部...为了使非预定义的插入数组工作,创建一个变量来保存数据输入页中的数组大小,并将删除更改为“插入表”准备语句并执行。
希望它能以某种方式帮助你
I was also once faced with a similar problem. My solution was to write my own min-recusive query. Just one query and it does the rest for you. Here is how it goes:
//main function
//delete function.. could as well setit up withn the factory function but 4 undestanging sake
}
Thats all... to make work for non-predefined insert array, crete a varible to hold the array size from your data entry page and change the delete to 'insert into table' prepare statement and execute.
Hope it has helped you in some way