3

I have a select query which works:

SELECT    actions.id
FROM      actions
LEFT JOIN users
ON        users.id = actions.user_id
WHERE     users.id is null;

And I wanted to delete these records. I tried changing the select line to "DELETE" which produced an error. I also tried a subquery:

DELETE FROM actions WHERE id IN (
    SELECT    actions.id
    FROM      actions
    LEFT JOIN users
    ON        users.id = actions.user_id
    WHERE     users.id is null
);

Both attempts cause errors. While I've already solved the problem via PHP, it seems like this ought to be something the database can do with a single command. Is there a way?

The query is basically selecting all the rows in actions that do not have a corresponding entry in users ( the tables in question are now using foreign keys so this issue won't happen again ).

3 Answers 3

5

Try this:

DELETE    actions
FROM     actions
LEFT JOIN users
ON        users.id = actions.user_id
WHERE     users.id is null;

More info at http://dev.mysql.com/doc/refman/5.0/en/delete.html

Sign up to request clarification or add additional context in comments.

Comments

2

MySQL doesn't like it if you try to DELETE/UPDATE rows and SELECT them in the same query. To solve this, they support a multi-table DELETE syntax.

DELETE a FROM actions a
LEFT OUTER JOIN users u ON u.id = a.user_id
WHERE u.id IS NULL; 

2 Comments

Thanks. By the way - recently bought your book. Good stuff.
Thanks! I'm glad that you enjoyed my book, SQL Antipatterns: Avoiding the Pitfalls of Database Programming. :-)
1
DELETE actions  
    FROM actions LEFT JOIN
    LEFT JOIN users
    ON        users.id = actions.user_id
    WHERE     users.id is null

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.