MySQL - 用COUNT更新,有可能吗?

时间:2013-10-17 16:04:46

标签: mysql sql

我正在尝试更新MySQL表格,如果“name”和“address_1”有重复的条目,则将列名“已处理”显示为“2”,但它不起作用 - 像往常一样我认为我只是有点白痴..

这是我正在尝试的事情

UPDATE `records`
SET `processed`='2', `count` = (SELECT COUNT(`user`)
FROM `records`
WHERE `name`<>''
AND `address_1`<>'')
WHERE `count`=> '1';

基本上,如果有多个'name'和'address_1',那么'processed'字段需要更新为'2'..

1 个答案:

答案 0 :(得分:1)

您可以使用类似这样的查询来返回重复的名称和地址:

SELECT name, address_1, COUNT(*) cnt
FROM records
GROUP BY name, address_1
HAVING COUNT(*)>1

然后将此查询加入记录表,并将处理的列更新为2,其中连接成功:

UPDATE
  records INNER JOIN (SELECT name, address_1, COUNT(*) cnt
                      FROM records
                      GROUP BY name, address_1
                      HAVING COUNT(*)>1) duplicates
  ON records.name = duplicates.name
     AND records.address_1=duplicates.address_1
SET
  `processed`='2',
  `count` = duplicates.cnt
WHERE 
  records.`name`<>''
  AND records.`address_1`<>''