¿Cómo puedo simular OFFSET en una instrucción UPDATE de MySQL?

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'

Me gustaría actualizar el 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

preguntado el 01 de febrero de 12 a las 03:02

2 Respuestas

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

Respondido 01 Feb 12, 08:02

Can you explain what the a and ? syntax does? I've seen thing sort of 'trick' in other queries and I've been unable to understand it even after reading up on what's happening. - T. Brian Jones

La ? is a parameter placeholder generally used in declaraciones preparadas given a suitably sophisticated client (like PHP's PDO extension) - Phil

OK, I'm clear on the ? and PDO. Now what does UPDATE articles a y SELECT 1 FROM articles sub do? Specifically, I mean the a y sub. Is that a shortcut for articles as a allowing us to access data from the outer query in the inner query without a conflict? - T. Brian Jones

Yes, it's a table alias. The AS keyword is optional - Phil

I think I'm clear on the function. Now I get this error, which seems to contradict what I thought I understood: You can't specify target table 'a' for update in FROM clause - T. Brian Jones

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

Respondido 01 Feb 12, 09:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.