我正在尝试使用以下代码合并MySQL中的行:
SELECT
type,
name,
GROUP_CONCAT(code SEPARATOR ',') AS code
FROM
`table1`
WHERE
name = '%name%' AND type = 'type'
GROUP BY
name
但是,DB条目没有发生变化,这是第一个问题。
数据库如下所示:
type | name | code
-----|-------|-------
A | Milk2 | 143521
-----|-------|-------
A | Milk3 | 987564
-----|-------|-------
B | Oil | 656435
-----|-------|-------
我试图让它看起来像:
type | name | code
-----|-------|---------------
A | Milk | 143521, 987564
-----|-------|---------------
B | Oil | 656435
-----|-------|---------------
如您所见,名称可能略有不同,因此这是另一个问题。 我想知道是否有任何方法合并行,比如名称的前四个字母匹配?
提前致谢。
答案 0 :(得分:0)
MySQL有几个string functions可能有所帮助。有LEFT(名称,4),您可能还想查看SOUNDEX(名称),它实现了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)
我希望这有用!
答案 1 :(得分:0)
您无法在此使用GROUP BY name
,因为名称始终不同,使用通配符时需要使用LIKE
而不是=
。
以下内容应该为您提供您正在寻找的结果
SELECT
type , name, GROUP_CONCAT( code SEPARATOR ',' ) AS all_codes
FROM `table1`
name LIKE '%name%' AND type = 'type'