Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all orphan records in MySQL?

Tags:

sql

mysql

I have 3 tables MySQL (MyIsam):

user (id), message (id, userId, ...), archivedMessage (id, userId, ...)

How can I delete all the users having no message AND no archivedMessage?

like image 584
Toto Avatar asked Jan 26 '11 13:01

Toto


People also ask

How do I purge old data in MySQL?

To delete all rows older than 30 days, you need to use the DELETE with INTERVAL. Use < now() i.e. less than operator to get all the records before the current date.

How do I DELETE a lot of rows in MySQL?

We can use DELETE statement along with a WHERE clause, which identifies those multiple rows, to delete multiple rows from MySQL table.

Which MySQL command is used to remove all records from a table in MySQL?

The MySQL DELETE Statement The DELETE statement is used to delete existing records in a table.

Is deletion possible in MySQL?

You can specify multiple tables in a DELETE statement to delete rows from one or more tables depending on the condition in the WHERE clause. You cannot use ORDER BY or LIMIT in a multiple-table DELETE .


1 Answers

You could use not exists:

delete from user
where not exists (select * from message m where m.userid = user.id)
      and not exists (select * from archivedMessage am where am.userid = user.id)
like image 105
Andomar Avatar answered Nov 15 '22 19:11

Andomar