如果单元格重复,则用新值更新单元格

Update cell with new value if its a duplicate

我有 table 种植物,其中一些具有相同的通用名称。如果该植物与其他植物共用一个通用名称,我想在通用名称后的括号中加上属和种,以免混淆。值得注意的是,并不是所有的植物都有一个共同的名字。

为了测试它,我创建了一个 common_name2 列。

我写了以下脚本:

UPDATE `plants` 
    SET `common_name2` = CONCAT(`common_name`, ' (', `genus`, ' ', `species`, ')') 
WHERE `common_name` != '' 
GROUP BY `common_name`  
HAVING COUNT(`common_name`) > 1

但我收到以下错误,我无法弄清楚:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near GROUP BY common_name HAVING COUNT('common_name') > 1 at line 1

你不能这样做:你的 GROUP BY 与你的 SET CONCAT 不一致。

操作方法如下:

UPDATE `plants` 
SET `common_name2` = CONCAT(`common_name`, ' (', `genus`, ' ', `species`, ')') 
WHERE `common_name` IN (
    select `common_name`
    FROM (select * from `plants`) plants
    WHERE `common_name` != '' 
    GROUP BY `common_name`  
    HAVING COUNT(`common_name`) > 1
)

SQL Fiddle

MySQL 5.6 架构设置:

CREATE TABLE plants
    (`id` int, `common_name` varchar(50), `common_name2` varchar(50), `genus` varchar(9), `species` varchar(12))
;

INSERT INTO plants
    (`id`, `common_name`, `common_name2`, `genus`, `species`)
VALUES
    (1, 'Roses', NULL, 'Rosa', 'Hulthemia'),
    (2, 'Roses', NULL, 'Rosa', 'Hesperrhodos'),
    (3, 'Roses', NULL, 'Rosa', 'Platyrhodon'),
    (4, 'Roses', NULL, 'Rosa', 'Rosa'),
    (5, 'Petunia', NULL, 'Petunia', 'axillaris'),
    (6, 'Petunia', NULL, 'Petunia', 'integrifolia'),
    (7, 'Cardinal', NULL, 'Lobelia', 'cardinalis'),
    (8, 'Anthurium', NULL, 'Anthurium', 'andraeanum')
;

UPDATE `plants` 
SET `common_name2` = CONCAT(`common_name`, ' (', `genus`, ' ', `species`, ')') 
WHERE `common_name` IN (
    select `common_name`
    FROM (select * from `plants`) plants
    WHERE `common_name` != '' 
    GROUP BY `common_name`  
    HAVING COUNT(`common_name`) > 1
)

查询 1:

select * from plants

Results:

| id | common_name |                   common_name2 |     genus |      species |
|----|-------------|--------------------------------|-----------|--------------|
|  1 |       Roses |         Roses (Rosa Hulthemia) |      Rosa |    Hulthemia |
|  2 |       Roses |      Roses (Rosa Hesperrhodos) |      Rosa | Hesperrhodos |
|  3 |       Roses |       Roses (Rosa Platyrhodon) |      Rosa |  Platyrhodon |
|  4 |       Roses |              Roses (Rosa Rosa) |      Rosa |         Rosa |
|  5 |     Petunia |    Petunia (Petunia axillaris) |   Petunia |    axillaris |
|  6 |     Petunia | Petunia (Petunia integrifolia) |   Petunia | integrifolia |
|  7 |    Cardinal |                         (null) |   Lobelia |   cardinalis |
|  8 |   Anthurium |                         (null) | Anthurium |   andraeanum |