如何在逗号分隔字符串字段上汇总两个表?
在一个表中,我有一个由逗号分隔的多个值的列。在第二个中,具有ID
和名称
的列。我需要得到用斜线隔开的名字。
表1:
ID | 值 | 1 | value2 |
---|---|---|---|
1 | ABCD | 1,2,3 | EFGH |
2 | IJKL | 1,4,6 | MNOP |
Table2:
ID | 名称 |
---|---|
1 | 1AB |
2 | 2CD |
2 CD 2 CD 3 3 3 | 3 3 |
3 | 3 3 |
3 3 | 5ij |
6 | 6kl |
SELECT
a.*,
GROUP_CONCAT(b.name,'/') groupedName
FROM
table1 a
LEFT JOIN
table2 b ON b.id IN (a.ids)
WHERE
a.id = 1
结果:
ID | value1 | IDS | IDS值2 | value2 groupedname |
---|---|---|---|---|
1 ABCD 1 ABCD 1 | ABCD | 1 ABCD 1,2 ,3 | EFGH | 1AB/2CD/3EF |
In one table I have a column with multiple values separated by a comma. In the second, columns with id
and name
. I need to get names separated by a slash.
Table1:
id | value1 | ids | value2 |
---|---|---|---|
1 | abcd | 1,2,3 | efgh |
2 | ijkl | 1,4,6 | mnop |
Table2:
id | name |
---|---|
1 | 1AB |
2 | 2CD |
3 | 3EF |
4 | 4GH |
5 | 5IJ |
6 | 6KL |
SELECT
a.*,
GROUP_CONCAT(b.name,'/') groupedName
FROM
table1 a
LEFT JOIN
table2 b ON b.id IN (a.ids)
WHERE
a.id = 1
Result:
id | value1 | ids | value2 | groupedName |
---|---|---|---|---|
1 | abcd | 1,2,3 | efgh | 1AB/2CD/3EF |
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设
ID
是table1
的主要键,请在 on 中使用operator one 等条款:请参阅
Assuming that
id
is the primary key oftable1
, use the operatorLIKE
in theON
clause like this:See the demo.
鉴于您的“ table1.ids ”具有
varchar(n)
类型,您可以使用喜欢
功能,以适应JOIN 在两个表之间,然后应用
group_concat
聚合函数:检查demo 此处。
Given that your "Table1.ids" has
VARCHAR(n)
type, you can use theLIKE
function for the matching condition on theJOIN
between the two tables, only then apply theGROUP_CONCAT
aggregation function:Check the demo here.