简体   繁体   中英

DELETE FROM 2 tables with JOIN (SQL)

DELETE `table1`, `table2` FROM `table1` JOIN `table2` ON table2.col = table1.id WHERE table1.id = 1

If in table2 no result with table2.col = table1.id then it sql query doesn't work. If table2 has row with col = table.id then it works perfectly. How to remake it? I need to delete row fom table1 even if in table2 row with table.col = table1.id doesn't exists.

Thanks in advance.

Use a LEFT JOIN .

DELETE `table1`, `table2` 
FROM `table1` 
LEFT JOIN `table2` ON table2.col = table1.id 
WHERE table1.id = 1

The general rule is that a DELETE query will delete the same rows that would be returned if you did a SELECT query with the same parameters. Since you would use a LEFT JOIN in a SELECT to get rows from table1 that have no match in table2 , you have to do the same thing with DELETE .

This general rule is also helpful if you want to test a DELETE safely. Perform the corresponding SELECT , and make sure it returns only the rows you want to delete.

You should use a LEFT JOIN in other to achieve this:

DELETE `table1`, `table2` 
FROM `table1` 
LEFT JOIN `table2` 
ON table2.col = table1.id WHERE table1.id = 1

Take a look here for further documentation:

http://www.w3schools.com/sql/sql_join_left.asp

Hope it helps.

You may try like this using the LEFT JOIN :

DELETE `table1`, `table2` 
FROM `table1` LEFT JOIN `table2` ON table2.col = table1.id WHERE table1.id = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM