是否可以将多行和多表中的字符串连接到一个结果列中? [英] Is it possible to concatenate strings from multiple rows and tables into one result column?

查看:23
本文介绍了是否可以将多行和多表中的字符串连接到一个结果列中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 MySQL 查询,该查询从与表标签"具有一对多关系的项目"表中检索一条记录.我的应用程序使用 4 个表来执行此操作:

I am trying to write a MySQL query that retrieves one record from table "projects" that has a one-to-many relationship with table "tags". My application uses 4 tables to do this:

Projects - the projects table
Entities - entity table; references several application resources
Tags - tags table
Tag_entity - links tags to entities

是否可以通过将表Tags"中的多个值连接到一个结果列的方式编写查询?我更喜欢这样做而不使用子查询.

Is it possible to write the query in such a way that multiple values from table "Tags" are concatenated into one result column? I'd prefer doing this without using subqueries.

表格说明:

                                      -------------
                                     | Tag_Entity  |
 -------------       ----------      | ----------- |      -------
| Projects    |     | Entities |     | - id        |     | Tags  |
| ----------- |     | -------- |     | - tag_id    |     | ----- |
| - id        | --> | - id     | --> | - entity_id | --> | id    |
| - entity_id |      ----------       -------------      | name  |
 -------------                                            -------

想要的结果:

Projects.id   Entities.id   Tags.name (concatenated)
1             5             'foo','bar','etc'

推荐答案

参见 GROUP_CONCAT

示例:

mysql> SELECT * FROM blah;
+----+-----+-----------+
| K  | grp | name      |
+----+-----+-----------+
|  1 |   1 | foo       |
|  2 |   1 | bar       |
|  3 |   2 | hydrogen  |
|  4 |   4 | dasher    |
|  5 |   2 | helium    |
|  6 |   2 | lithium   |
|  7 |   4 | dancer    |
|  8 |   3 | winken    |
|  9 |   4 | prancer   |
| 10 |   2 | beryllium |
| 11 |   1 | baz       |
| 12 |   3 | blinken   |
| 13 |   4 | vixen     |
| 14 |   1 | quux      |
| 15 |   4 | comet     |
| 16 |   2 | boron     |
| 17 |   4 | cupid     |
| 18 |   4 | donner    |
| 19 |   4 | blitzen   |
| 20 |   3 | nod       |
| 21 |   4 | rudolph   |
+----+-----+-----------+
21 rows in set (0.00 sec)

mysql> SELECT grp, GROUP_CONCAT(name ORDER BY K) FROM blah GROUP BY grp;
+-----+----------------------------------------------------------------+
| grp | GROUP_CONCAT(name ORDER BY K)                                  |
+-----+----------------------------------------------------------------+
|   1 | foo,bar,baz,quux                                               |
|   2 | hydrogen,helium,lithium,beryllium,boron                        |
|   3 | winken,blinken,nod                                             |
|   4 | dasher,dancer,prancer,vixen,comet,cupid,donner,blitzen,rudolph |
+-----+----------------------------------------------------------------+
4 rows in set (0.00 sec)

这篇关于是否可以将多行和多表中的字符串连接到一个结果列中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆