当名称略有不同时按名称合并 mysql 行

merge mysql rows by name when names are slightly different

我正在尝试使用以下代码合并 MySQL 中的行:

SELECT
    type,
    name,
    GROUP_CONCAT(code SEPARATOR ',') AS code
FROM
    `table1`
WHERE
    name = '%name%' AND type = 'type'
GROUP BY
    name

然而,数据库条目没有发生任何变化,这是第一个问题。

数据库如下所示:

type | name  | code
-----|-------|-------
 A   | Milk2 | 143521
-----|-------|-------
 A   | Milk3 | 987564
-----|-------|-------
 B   | Oil   | 656435
-----|-------|-------

我想让它看起来像:

type | name  | code
-----|-------|---------------
 A   | Milk  | 143521, 987564
-----|-------|---------------
 B   | Oil   | 656435
-----|-------|---------------

如您所见,名称可能略有不同,这是另一个问题。 我想知道当名字的前四个字母匹配时是否有任何方法可以合并行?

提前致谢。

MySQL 有几个 string functions which might help. There's LEFT(name, 4) and you might also want to look at SOUNDEX(name), which implements the Soundex algorithm 来散列听起来相似的单词。例如:

 select soundex('smith'), soundex('smythe')

+ --------------------- + ---------------------- +
| soundex('smith')      | soundex('smythe')      |
+ --------------------- + ---------------------- +
| S530                  | S530                   |
+ --------------------- + ---------------------- +
1 rows

或者,使用您问题中的示例:

select soundex('milk2'), soundex('milk3')

+ --------------------- + --------------------- +
| soundex('milk2')      | soundex('milk3')      |
+ --------------------- + --------------------- +
| M420                  | M420                  |
+ --------------------- + --------------------- +
1 rows

您的查询将如下所示:

SELECT
    type,
    GROUP_CONCAT(DISTINCT(name) SEPARATOR ',') AS name,  // note that since you've grouped on SOUNDEX(name) you can't just select name (MySQL may let you but will choose the first one
    GROUP_CONCAT(code SEPARATOR ',') AS code
FROM
    `table1`
WHERE
    name LIKE '%name%' AND type = 'type'
GROUP BY
    type, SOUNDEX(name)

希望对您有所帮助!

此处不能使用GROUP BY name,因为名称总是不同的,使用通配符时需要使用LIKE而不是=

以下内容应该可以为您提供所需的结果

SELECT 
 type , name, GROUP_CONCAT( code SEPARATOR  ',' ) AS all_codes
FROM  `table1` 
name LIKE '%name%' AND type = 'type'