【问题标题】:SQL join and group items as an arraySQL 将项目连接和分组为数组
【发布时间】:2015-01-06 22:40:21
【问题描述】:

我有以下 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"],
]

(只有 2 篇文章但三行)

有没有办法让它返回带有标签数组的每篇文章?

类似:

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

【问题讨论】:

  • 你能发布你的表创建吗?可能更容易生成字符串格式的“数组”

标签: mysql sql join


【解决方案1】:

默认情况下你不能返回一个数组。但是您可以装饰/连接您的列以生成类似字符串的数组。如果这是个好主意?取决于你的情况。另外请注意 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

PS:没有测试过上面的代码。测试一下:)

【讨论】:

    【解决方案2】:
    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 '#') 用于“胶水”的字符,该字符不应出现在任何名称中,因此可以安全地拆分到数组中。

    【讨论】:

    • @RaphaëlAlthaus SQL 没有数组的概念。
    • 在mysql中不能返回数组,但是在PHP端可以得到这个串接的字符串,拆分成数组
    • @BaconBits 确实如此。所以答案应该解释这一点(所以现在很好;))
    • @RaphaëlAlthaus 我不同意。那将是迂腐的。 StackOverflow 不是我们描述语言基本概念的地方。
    • @BaconBits 这是我尊重的观点:我的意思是,如果一个问题是关于返回一个数组(这是不可能的),并且你给出一个连接字符串的答案,你应该解释你为什么给出那个答案(这可能很好)。但这也只是一个 PoV。
    猜你喜欢
    • 1970-01-01
    • 2017-03-03
    • 2017-11-21
    • 1970-01-01
    • 2011-03-14
    • 2019-03-09
    • 2023-04-01
    • 2021-10-13
    • 2021-06-01
    相关资源
    最近更新 更多