简体   繁体   English

如何在MySQL UPDATE语句中模拟OFFSET?

[英]How can I simulate OFFSET in a MySQL UPDATE statement?

I have a MySQL database table that contains an Article ID ( primary key ) and an Article Title. 我有一个MySQL数据库表,其中包含文章ID(主键)和文章标题。 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: 然后我使用foreach循环和此命令将所有重复的标题替换为空白:

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. 我想更新articles表并使用类似的东西替换除第一个条目之外的所有重复标题,基于文章ID ASC。 The problem is that OFFSET doesn't seem to work in an UPDATE. 问题是OFFSET似乎不能在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
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 更新存在具有相同标题和较低ID的匹配文章的所有文章

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. 我从此计数中减去一个,然后通过ID DESC命令我的UPDATE查询,然后将查询限制为计数减1。 This serves the same purpose and removes all duplicates except for the first entry. 这用于相同的目的并删除除第一个条目之外的所有重复项。

Here is the UPDATE query I use: 这是我使用的UPDATE查询:

UPDATE articles
SET title = ''
WHERE title = '$duplicate_title'
ORDER BY id DESC
LIMIT $duplicate_count_minus_one

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM