Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I simulate OFFSET in a MySQL UPDATE statement?

Tags:

mysql

offset

I have a MySQL database table that contains an Article ID ( primary key ) and an Article Title. I want to remove duplicate titles from the table, but keep the first occurrence of the title. I initially simply did a query for all duplicate titles:

SELECT
    title,
    count( id ) AS count
FROM articles
GROUP BY title
HAVING count > 1

Then I replaced all the duplicate titles with a blank using a foreach loop and this command:

UPDATE articles
SET title = ''
WHERE title = '$duplicate_title'

I'd like to update the articles table and replace all duplicate titles except the first entry, based on the Article ID ASC using something like this. The problem is that OFFSET doesn't seem to work in an UPDATE. Is there a way to do this in a single query?

UPDATE articles
SET title = ''
WHERE title = '$duplicate_title'
ORDER BY id ASC
OFFSET 1
like image 882
T. Brian Jones Avatar asked Nov 05 '22 06:11

T. Brian Jones


2 Answers

UPDATE articles a
INNER JOIN articles b
    ON a.title = b.title AND a.ID > b.ID
SET title = '';

This basically says

update all articles where there exists a matching article with the same title and a lower ID

like image 70
Phil Avatar answered Nov 07 '22 21:11

Phil


I found another solution that was a little outside the scope of my original question, but relevant nonetheless.

I already had a count of duplicates from the first query that found them. I subtracted one from this count, then ordered my UPDATE query by ID DESC and then LIMITed the query to the count minus one. This serves the same purpose and removes all duplicates except for the first entry.

Here is the UPDATE query I use:

UPDATE articles
SET title = ''
WHERE title = '$duplicate_title'
ORDER BY id DESC
LIMIT $duplicate_count_minus_one
like image 45
T. Brian Jones Avatar answered Nov 07 '22 21:11

T. Brian Jones