I’m going to delete some rows in one of my table called sy_user
. I want to delete some of the rows that is not matched in the other table, which is the tb_master_pegawai
.
How do i solve this query to do the row delete using the subquery as the WHERE
condition?
I used subquery as the WHERE
condition in the DELETE
query.
When i run it in phpmyadmin it says
You can’t specify target table ‘sy_user’ for update in FROM clause
But when i simulate it, it has return rows.
DELETE FROM sy_user
WHERE user_id NOT IN
(SELECT tbpeg.ID
FROM tb_master_pegawai AS tbpeg
JOIN sy_user AS tbuser ON tbpeg.ID=tbuser.user_id)
I expect the result is i have deleted the rows that are not matched with the same data in the other table.
2
Answers
You could simplify your request using only a LEFT JOIN:
You can’t reference your the table you are deleting from in a subquery of
DELETE
/UPDATE
queries. Instead, use aLEFT JOIN
and check where the joined table isNULL
(meaning it had no rows that matched theON
condition).Try to run delete queries within a transaction when testing it, that way you can rollback if the query deleted more rows than intended.