3

I'm trying to delete duplicate rows according to some fileds. When I'm running the query below:

delete
    from slowmo_vid as sv1, slowmo_vid as sv2
    where sv1.video_id = '2luh6g3ni5ex'
    and sv1.slowmo_end_t<=sv2.slowmo_end_t;

I'm getting the error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'as sv1, slowmo_vid as sv2
where sv1.video_id = '2luh6g3ni5ex'
and sv1.slowmo_end' at line 2

The fields of the tables are : id, video_id internal_uri, slowmo_end_t

1
  • if you wan't use multi Tables for the DELETE use the JOIN statement instead of FROM Table1, Table2 Commented Dec 7, 2015 at 9:15

3 Answers 3

5

You seem to be trying to do an ANSI-92 style inner join inside a DELETE statement. But the WHERE clause cannot simultaneously be used to enforce the join and enforce a restriction on a result set. Instead, do the following explicit INNER JOIN to remove the records you want. Notice that it is clear what role the WHERE clause is playing.

Update: If you want to delete all records except for the one containing the max video_id then you can add a nested subquery to the WHERE clause.

DELETE sv1.*
FROM slowmo_vid sv1
INNER JOIN slowmo_vid sv2 ON sv1.slowmo_end_t <= sv2.slowmo_end_t
WHERE sv1.video_id = '2luh6g3ni5ex' AND
    sv1.video_id <> (SELECT x.id
                     FROM (SELECT MAX(t.video_id) AS id 
                             FROM slowmo_vid t) x)
Sign up to request clarification or add additional context in comments.

4 Comments

When I'm running the query its delete all the records that satisfy this condition. Is there a way to delete all of the records except one? I tried to add limit 1 at the end of the query but it didn't help
Which record do you wish to keep and what is the logic behind this decision?
I want to keep the record with max id because it have more updated data
I updated the query. Give it a whirl and let us know if you have any problems.
0

You can specify multiple tables in a DELETE statement to delete rows from one or more tables depending on the particular condition in the WHERE clause. However, you cannot use ORDER BY or LIMIT in a multiple-table DELETE. The table_references clause lists the tables involved in the join. Its syntax is described in Section 12.2.8.1, “JOIN Syntax”.

http://dev.mysql.com/doc/refman/5.6/en/delete.html

The example in the manual is:

DELETE t1, t2 FROM t1 INNER JOIN t2 INNER JOIN t3
WHERE t1.id=t2.id AND t2.id=t3.id;

Comments

-2

You cannot use aliases on DELETE statement. You can try with:

DELETE FROM myAlias USING `my_table` AS myAlias

Or try without any aliases

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.