仅更新MySQL中重复条目的第一条记录

时间:2011-10-01 11:46:58

标签: php mysql

问题解决了!

更新

不太正确我需要的东西,让我们在带有字段ID,NAME,COVER

的简单表上做例子

我有100个条目有100个名字,有些名称是重复的,但我只想从重复项中更新第一个。


尝试更新数据库中所有重复项的所有第1行,真的很难做到,我知道如何制作它?下面是我试图重建的代码,但是这个代码用最后一个替换所有重复的代码。

架构,我希望它如何工作

ID NAME COVER
1  Max   1
2  Max   0
3  Andy  1
4  Andy  0
5  Andy  0

UPDATE table t
  JOIN (
    SELECT MinID, b.Name LatestName
    FROM table b
    JOIN (
      SELECT MIN(ID) MinID, MAX(ID) MaxID
      FROM table
      GROUP BY tag
      HAVING COUNT(*) > 1
    ) g ON b.ID = g.MaxID
  ) rs ON t.ID = rs.MinID
SET t.Name = LatestName;

3 个答案:

答案 0 :(得分:7)

根本不清楚你想要什么。也许这个:

UPDATE table AS t
  JOIN 
    ( SELECT MIN(ID) MinID
      FROM table
      GROUP BY Name
      HAVING COUNT(*) > 1
    ) AS m 
    ON t.ID = m.MinID
SET t.Cover = 1 ;

对于这个(和将来的)问题,请记住,当你写一个问题时:

1. a description of your problem, as clear as possible    --- you have that
2. data you have now (a few rows of the tables)           --- ok, nice
3. the code you have tried                 --- yeah, but better use same names
                                           --- as the data and description above
4. the error you get (if you get an error)      --- doesn't apply here
5. the result you want (the rows after the update in your case)
                                       --- so we know what you mean in case we 
                                       --- haven't understood from all the rest 

答案 1 :(得分:0)

我最近在PostgreSQL中做过这个。您是否可以使用临时表?如果是这样,对于每个重复集,将MIN()主键插入临时表,然后使用临时表中的PK使用where子句执行UPDATE。

编辑:关注你的评论,这是我最近做的事情。

CREATE TEMPORARY TABLE misc_updates (
    temp_oid INTEGER,
    job INTEGER,
    run CHARACTER VARYING(8),
    quantity INTEGER
);

INSERT INTO misc_updates (temp_oid, job, run, quantity)
SELECT
    MAX(runjob.oid) temp_oid, runjob.job, runjob.run, SUM(runjob.quantity) sum_quantity
FROM
    runjob
INNER JOIN job ON (runjob.job = job.code)
INNER JOIN
    (SELECT run, job FROM runjob GROUP BY run, job HAVING COUNT(*) > 1) my_inner
    ON (runjob.run = my_inner.run AND runjob.job = my_inner.job)
GROUP BY
    runjob.job, runjob.run, job.quantity
;

/* Do updates on one of the duplicated runjob rows */
UPDATE runjob
    SET quantity = mu.quantity
FROM
    misc_updates mu
WHERE
    runjob.oid = mu.temp_oid;

您可以将'oid'替换为主键(我的问题是该表没有主键!)。同样重要的是UPDATE中的where子句,因此只更新了一些行。您需要将MAX()替换为MIN(),当然还要将行更改为用例中的行。请记住,这适用于PostgreSQL,但方法应该大致相同。

答案 2 :(得分:0)

使用子查询作为选择标准:

UPDATE table t SET t.Name = LatestName
WHERE ID = 
    (SELECT ID FROM table WHERE 
         (
            SELECT COUNT(DISTINCT(Name)) FROM table WHERE Name = 'duplicate'
         ) > 1 
     LIMIT 1)