Phenomenon: When performing update and delete operations, if there is a subquery statement in the conditional statement, an error 1093 will be reported at this time!
Error log: 1093 - You can't specify target table 't_suer_study_video' for update in FROM clause
First query according to the conditions
SELECT * FROM t_suer_study_video WHERE video_course_id =207;
As shown in the figure below, one of the users has two pieces of data, and the piece of data whose train_id is null is duplicate data, which I need to delete.
In the online environment, thousands of data like the previous page are accidentally generated, which is caused by a bug in the written program, so I need to delete them in batches, and first query them by user ID:
SELECT user_id, COUNT(*) FROM t_suer_study_video WHERE video_course_id =207 GROUP BY user_id;
As shown in the figure below, the data of users with a quantity of 2 needs to be processed,
and then filter the grouped user data
SELECT
user_id,
COUNT(*)
FROM
t_suer_study_video
WHERE
video_course_id = 207
GROUP BY
user_id
HAVING
COUNT(*) > 1;
In my test data, only one user is duplicated. In reality, there are multiple users.
Then delete the duplicates, which is to delete the duplicate user IDs obtained from the above grouping query as a condition.
DELETE
FROM
t_suer_study_video
WHERE
video_course_id = 207
AND train_id IS NULL
AND user_id IN (
SELECT
user_id
FROM
t_suer_study_video
WHERE
video_course_id = 207
GROUP BY
user_id
HAVING
COUNT(*) > 1
);
Error 1093 - You can't specify target table 't_suer_study_video' for update in FROM clause
Reason: When performing update and delete operations, there is a subquery statement in the conditional statement, and a 1093 error will be reported at this time! , MySQL will add a read lock (shared lock) when reading data, and other requests can add a read lock again, but cannot add a write lock. It will cause the data read by the current thread to be not the latest data, which is the non-repeatable read phenomenon). Therefore, it does not support query operations while updating data, and adding read locks does not allow adding write locks.
Solution: Nest one more layer of query outside, and use the original query as a subquery.
DELETE
FROM
t_suer_study_video
WHERE
video_course_id = 207
AND train_id IS NULL
AND user_id IN (
SELECT
a.user_id
FROM
(
SELECT
user_id
FROM
t_suer_study_video
WHERE
video_course_id = 207
GROUP BY
user_id
HAVING
COUNT(*) > 1
) a
);
successfully deleted