我正在尝试编写一个MySQL查询,从表“项目”中检索一条记录,该表与表“tags”具有一对多的关系。我的应用程序使用4个表来执行此操作:
Projects - the projects table
Entities - entity table; references several application resources
Tags - tags table
Tag_entity - links tags to entities
是否可以以表格“Tags”中的多个值连接成一个结果列的方式编写查询?我不喜欢在不使用子查询的情况下这样做。
表澄清:
-------------
| 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'
答案 0 :(得分:20)
请参阅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)
答案 1 :(得分:3)
我不知道它是否适用于MySQL,但在SQL Server中你可以使用一个技巧:
DECLARE @csv varchar(max)
SET @csv = ''
SELECT @csv = @csv + ',' + foo.SomeColumn
FROM [FOO] foo
WHERE foo.SomeId = @SomeId
然后在主要选择
SELECT ..., @csv AS [Tags]
FROM ...
SELECT @csv = @csv + ',' + foo.SomeColumn
行的结果是@csv
成为源表中所有匹配记录的逗号分隔列表(在谓词之后)。
值得在MySQL中尝试?