Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Delete row if id doesn't exist in other table

Tags:

mysql

I think this is newbie ask. How to delete row if id doesn't exist in other table? My thought is fetch the ids first and delete. I'm looking for better querying.

like image 888
Jeaf Gilbert Avatar asked Jul 29 '11 08:07

Jeaf Gilbert


People also ask

Can we delete a row from a table based on another table?

Deleting rows based on another table. Sometimes we need to delete rows based on another table. This table might exist in the same database or not. We can use the table lookup method or SQL join to delete these rows.

Can delete work without WHERE clause?

Example - DELETE Statement with One ConditionIf you run a DELETE statement with no conditions in the WHERE clause, all of the records from the table will be deleted. As a result, you will most often include a WHERE clause with at least one condition in your DELETE statement.

How do I remove a row from a null value in MySQL?

Use the delete command to delete blank rows in MySQL. delete from yourTableName where yourColumnName=' ' OR yourColumnName IS NULL; The above syntax will delete blank rows as well as NULL row.

Can delete have WHERE clause?

You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise all the records would be deleted.


1 Answers

You can set foreign keys to these tables.

More info here

for simple query, here it is:

 DELETE FROM table WHERE (SELECT count(1) FROM table2 WHERE id = table.id) < 1
like image 105
genesis Avatar answered Nov 15 '22 10:11

genesis