Mysql只更新具有唯一字段值的记录 - 如何?

时间:2013-05-04 05:57:48

标签: mysql

说我有一个mysql表:

ID, Name, Number
1, abc, 0
2, def, 0
3, def, 0
4, ghi, 0

我现在想在所有记录中更改字段'Number'(比如说1)的值,其中字段'Name'的值只出现一次(在本例中为记录1和记录4)。我如何以最简单的方式在mysql中做到这一点?

我是一个mysql初学者,并且已经搜索了很多这个问题,但没有找到解决方案 - 至少不是一个简单易懂的解决方案。

5 个答案:

答案 0 :(得分:2)

一个简单的请尝试使用mysql

update  [tablename] set number=1 
where id in (select id 
  from [tablename] 
  group by name 
  having count()=1) ) 

我可以尝试使用它们来解释我的语法错误。 嵌套查询将解决此问题,您将能够无缝地获得结果

祝你好运 如果您需要任何帮助,请告诉我我会写出确切的查询并给您。

答案 1 :(得分:1)

由于您使用的是MySQL,因此需要在更新查询中使用JOIN:

UPDATE
  yourtable t1 INNER JOIN (SELECT Name
                           FROM yourtable
                           GROUP BY Name
                           HAVING COUNT(*)=1) t2
  ON t1.Name=t2.Name
SET
  Number=1

请参阅小提琴here。或者您需要使用嵌套子查询:

UPDATE yourtable
SET Number=1 
WHERE id IN (SELECT * FROM (SELECT id FROM yourtable 
             GROUP BY name 
             HAVING COUNT(*)=1) s)

(请注意SELECT * FROM (...your subquery...)。小提琴是here

答案 2 :(得分:0)

绝对最简单的方法是使用子查询:

UPDATE mytable AS NumberUpdating SET Number = 42 WHERE NOT EXISTS (
    SELECT 1 FROM Number AS NumberTesting
    WHERE
        NumberTesting.ID != NumberUpdating.ID AND
        NumberTesting.Name == NumberUpdating.Name
)

这是做什么的更明显,但它可能不如JOIN那样高效:

UPDATE FROM mytables AS NumberUpdating
LEFT JOIN mytable AS NumberTesting ON
    NumberTesting.Name == NumberUpdating.name AND
    NumberTesting.ID != NumberUpdating.ID
WHEN NumberTesting.ID IS NULL
SET Number = 42

答案 3 :(得分:0)

(SELECT Name, COUNT(Name) GROUP BY Name)为您提供具有唯一名称的表格,并计算Name的出现次数。

UPDATE (SELECT ID, COUNT(name) GROUP BY Name)
SET Number = 1
WHERE COUNT(name) = 1

虽然没有测试,但希望它能引导你回答

答案 4 :(得分:0)

您可以使用: -

UPDATE Yourtable SET number=1 where ID in (Select id,count(name) as num from Yourtable group by name having num=1)