将SQL连接和分组项目作为数组

18

我有以下SQL语句

SELECT articles.id, articles.title, tags.name AS tags
FROM articles
LEFT JOIN article_tag_association ON articles.id = article_tag_association.article_id
LEFT JOIN tags ON tags.id = article_tag_association.tag_id
这个方法可以正常工作,但是对于每个标签,它都会创建一行,这会影响限制。
例如:
[
 "0" => ["id" => "1", "title" => "test", "tags" => "tag1"],
 "1" => ["id" => "1", "title" => "test", "tags" => "tag2"],
 "2" => ["id" => "2", "title" => "test2", "tags" => "tag1"],
]

有没有办法使其返回每篇文章以及标签数组?

类似于:

[
 "0" => ["id" => "1", "title" => "test", "tags" => ["tag1", "tag2"]],
 "1" => ["id" => "2", "title" => "test2", "tags" => ["tag1"]],
]

你能发布一下你的表格创建代码吗?这样生成格式化字符串“数组”可能会更容易。 - Krish
2个回答

13

默认情况下,您无法返回数组。但是,您可以装饰/连接您的列以生成类似于数组的字符串。这是否是一个好主意?取决于您的情况。另外,请注意MySQL对group_concat有一些限制(仅会返回1024 * chars)。

无论如何,仅供测试目的,您可以尝试以下操作:

SELECT 
    concat(
    '[',
    concat('ID => "', articles.id,'"'),
    concat('Title => "', articles.title,'"'),
    concat('Tags => [', GROUP_CONCAT(concat('"',tags.name, '"')), ']'),
    ']'
    ) as Array_String
FROM
    articles
        LEFT JOIN
    article_tag_association ON articles.id = article_tag_association.article_id
        LEFT JOIN
    tags ON tags.id = article_tag_association.tag_id
GROUP BY articles.id
这将以数组形式提供每一行的内容,如果您想将它们全部放在一行上,请将它们都放在group_concat下面。
注意:如果您的结果超过1024个字符,则必须使用。
SET group_concat_max_len = 1000000; >> size of your string length

提示:以上代码未经过测试,请进行测试:)


9
SELECT articles.id, articles.title, GROUP_CONCAT(tags.name) AS tags
FROM articles
LEFT JOIN article_tag_association ON articles.id = article_tag_association.article_id
LEFT JOIN tags ON tags.id = article_tag_association.tag_id
GROUP BY articles.id

在mysql中无法返回数组,但您可以获取此连接的字符串,并在PHP端将其拆分为数组。您可以选择一个用于“粘合”的字符,例如GROUP_CONCAT(name SEPARATOR '#'),其中'#'应该不会出现在任何名称中,因此对于拆分成数组是安全的。


2
@RaphaëlAlthaus SQL没有数组的概念。 - Bacon Bits
你不能在MySQL中返回一个数组,但是你可以获取这个连接的字符串,在PHP端将其拆分成一个数组。 - David162795
@BaconBits 确实。因此,答案应该解释清楚(所以现在没问题了;)) - Raphaël Althaus
1
@RaphaëlAlthaus 我不同意。那会显得太学究了。StackOverflow 不是我们描述语言基本概念的地方。 - Bacon Bits
@BaconBits 这是一个观点,我尊重:我的意思只是,如果一个问题是关于返回一个数组(这是不可能的),而你给出一个连接字符串的答案,你应该解释为什么你给出那个答案(这可能完全没问题)。但这也只是一个观点。 - Raphaël Althaus
如果@RaphaëlAlthaus重写他的答案,使其生成类似['val1','val2',...,'valn']的内容,那么这个字符串基本上就是一个数组。虽然不是典型的数组,但它是一个JSON数组。 - ITroubs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接