在一个查询中从两个表中删除
我有两个表在MySQL中
#messages table : messageid messagetitle . . #usersmessages table usersmessageid messageid userid . .
现在我想从邮件表中删除它没关系。 但是当我删除消息与messageid ='1'例如它仍然存在usersmessage我不得不从这两个表中删除一次;
所以我使用以下查询:
DELTE FROM messages LEFT JOIN usersmessages USING(messageid) WHERE messageid='1' ;
然后我testing
DELETE FROM messages , usersmessages WHERE messages.messageid = usersmessages.messageid and messageid='1' ;
但是这两个查询并不能完成这个任务。
你不能用分号分开吗?
Delete from messages where messageid = '1'; Delete from usersmessages where messageid = '1'
要么
只需使用INNER JOIN
如下
DELETE messages , usersmessages FROM messages INNER JOIN usersmessages WHERE messages.messageid= usersmessages.messageid and messages.messageid = '1'
DELETE a.*, b.* FROM messages a LEFT JOIN usersmessages b ON b.messageid = a.messageid WHERE a.messageid = 1
翻译:从message表中删除messageid = 1,如果表的uersmessages有messageid = messageid的表消息 ,则删除该行的uersmessages表。
您应该使用ON DELETE CASCADE
创build一个FOREIGN KEY
:
ALTER TABLE usersmessages ADD CONSTRAINT fk_usermessages_messageid FOREIGN KEY (messageid) REFERENCES messages (messageid) ON DELETE CASCADE
,或者在事务中使用两个查询:
START TRANSACTION;; DELETE FROM usermessages WHERE messageid = 1 DELETE FROM messages WHERE messageid = 1; COMMIT;
但事务只影响InnoDB
表。
你有两个select:
首先,在一个交易中做两个陈述:
BEGIN; DELETE FROM messages WHERE messageid = 1; DELETE FROM usermessages WHERE messageid = 1; COMMIT;
或者,您可以使用外键设置ON DELETE CASCADE。 这是更好的方法。
CREATE TABLE parent ( id INT NOT NULL, PRIMARY KEY (id) ); CREATE TABLE child ( id INT, parent_id INT, FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE );
你可以在这里阅读关于ON DELETE CASCADE的更多信息。
DELETE message.*, usersmessage.* from users, usersmessage WHERE message.messageid=usersmessage.messageid AND message.messageid='1'
不需要连接:
DELETE m, um FROM messages m, usersmessages um WHERE m.messageid = 1 AND m.messageid = um.messageid
试试这个请
DELETE FROM messages,usersmessages USING messages INNER JOIN usermessages on (messages.messageid = usersmessages.messageid) WHERE messages.messsageid='1'
尝试这个..
DELETE a.*, b.* FROM table1 as a, table2 as b WHERE a.id=[Your value here] and b.id=[Your value here]
我让id
作为示例列。
很高兴这有助于。 🙂