Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete MySQL row using where clause

Tags:

sql

mysql

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

like image 524
liorko Avatar asked May 27 '26 11:05

liorko


1 Answers

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)
like image 75
Tim Biegeleisen Avatar answered May 30 '26 06:05

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!