是否可以将多行和多表中的字符串连接到一个结果列中?

2021-12-17 00:00:00 join select mysql database-design

我正在尝试编写一个 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)

相关文章