[英]delete rows from multiple tables
我正在嘗試使用SQL從連接在一起的多個表中刪除多個行。
表A與表B相連。表B與表C相連
我想刪除表B和C中與表A中的行對應的所有行
CREATE TABLE `boards` (
`boardid` int(2) NOT NULL AUTO_INCREMENT,
`boardname` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`boardid`)
);
-- --------------------------------------------------------
--
-- Table structure for table `messages`
--
CREATE TABLE `messages` (
`messageid` int(6) NOT NULL AUTO_INCREMENT,
`boardid` int(2) NOT NULL DEFAULT '0',
`topicid` int(4) NOT NULL DEFAULT '0',
`message` text NOT NULL,
`author` varchar(255) NOT NULL DEFAULT '',
`date` datetime DEFAULT NULL,
PRIMARY KEY (`messageid`)
);
-- --------------------------------------------------------
--
-- Table structure for table `topics`
--
CREATE TABLE `topics` (
`topicid` int(4) NOT NULL AUTO_INCREMENT,
`boardid` int(2) NOT NULL DEFAULT '0',
`topicname` varchar(255) NOT NULL DEFAULT '',
`author` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`topicid`)
);
如果您使用帶有“on delete cascade”的外鍵,則可以通過db-system完成此操作。
看看這里: http : //dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
你可以只是檢查存在
delete from topics where boardid in (select boardid from boards)
delete from messages where boardid in (select boardid from boards)
但是,只有這種行為不應該總是適用時才有意義。 當應始終應用該行為時,在級聯上使用delete實現外鍵
在zali網站上,在你的幫助文件和這里解釋
從多個表中刪除行可以通過兩種方式完成:
多表DELETE語句可以用兩種格式編寫。 以下示例演示了一種語法,用於從表t1中刪除行的查詢,其中id值與表t2中的值相匹配:
DELETE t1 FROM t1, t2 WHERE t1.id = t2.id;
第二種語法略有不同:
DELETE FROM t1 USING t1, t2 WHERE t1.id = t2.id;
要從兩個表中刪除匹配的記錄,語句為:
DELETE t1, t2 FROM t1, t2 WHERE t1.id = t2.id;
DELETE FROM t1, t2 USING t1, t2 WHERE t1.id = t2.id;
當這些語句用於多表操作時,不允許UPDATE和DELETE通常支持的ORDER BY和LIMIT子句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.