9

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

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

是否可以以将表“标签”中的多个值连接到一个结果列中的方式编写查询?我宁愿这样做而不使用子查询。

表格说明:

                                      -------------
                                     | 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'
4

2 回答 2

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)
于 2008-12-29T13:42:35.693 回答
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.SomeColumnline的结果是@csv源表中所有匹配记录的逗号分隔列表(在谓词之后)。

值得在 MySQL 中尝试吗?

于 2008-12-29T13:29:37.997 回答