Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete from two tables in one query

Tags:

sql

mysql

I have two tables in MySQL

#messages table  : 
messageid
messagetitle 
.
.

#usersmessages table 
usersmessageid 
messageid
userid
.
.

Now if I want to delete from messages table it's ok. But when I delete message by messageid the record still exists on usersmessage and I have to delete from this two tables at once.

I used the following query :

DELETE FROM messages LEFT JOIN usersmessages USING(messageid) WHERE messageid='1' ; 

Then I test

   DELETE FROM messages , usersmessages 
   WHERE messages.messageid = usersmessages.messageid 
   and messageid='1' ; 

But these two queries are not accomplishing this task .

like image 953
mehdi Avatar asked Aug 05 '09 14:08

mehdi


People also ask

How delete all records from multiple tables in SQL?

To remove one or more rows in a table: First, you specify the table name where you want to remove data in the DELETE FROM clause. Second, you put a condition in the WHERE clause to specify which rows to remove. If you omit the WHERE clause, the statement will remove all rows in the table.

How do you delete data from 3 tables in SQL?

If it works if all tables have records, try using LEFT JOIN instread of INNER JOIN. Also, You had some mess with Your joins ON conditions. Try it like this: delete relativedata, crawls, stored from relativedata LEFT join crawls on relativedata.

How can I delete data from multiple tables in a single query in db2?

You should use a with statement to create a temporary table with the I'd of the row/foreign keys you want to delete.


2 Answers

Can't you just separate them by a semicolon?

Delete from messages where messageid = '1';
Delete from usersmessages where messageid = '1'

OR

Just use INNER JOIN as below

DELETE messages , usersmessages  FROM messages  INNER JOIN usersmessages  
WHERE messages.messageid= usersmessages.messageid and messages.messageid = '1'
like image 200
Eric Avatar answered Oct 26 '22 17:10

Eric


DELETE a.*, b.* 
FROM messages a 
LEFT JOIN usersmessages b 
ON b.messageid = a.messageid 
WHERE a.messageid = 1

translation: delete from table messages where messageid =1, if table uersmessages has messageid = messageid of table messages, delete that row of uersmessages table.

like image 55
angry kiwi Avatar answered Oct 26 '22 16:10

angry kiwi