Is it possible to concatenate strings from multiple rows and tables into one result column?(是否可以将多行和多表中的字符串连接到一个结果列中?)
问题描述
我正在尝试编写一个 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)
这篇关于是否可以将多行和多表中的字符串连接到一个结果列中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以将多行和多表中的字符串连接到一个结果列中?


基础教程推荐
- Sql Server 字符串到日期的转换 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01