【问题标题】:How to get nested array from MySQL select with joins如何通过连接从 MySQL 选择中获取嵌套数组
【发布时间】:2012-07-18 01:26:59
【问题描述】:

我有模型用户、帖子、评论和标签。

  • 用户创建帖子。
  • 帖子可以有多个评论和标签。

每个模型都有自己的表格,因此有表格“posts”、“cmets”和“tags”。评论有一个外键“post_id”,而标签有一个名为“post_tags”的many_to_many关系表,其中有两个字段:“post_id”和“tag_id”。

我想得到一个嵌套数组,如下所示:

  • 我应该运行哪些 MySQL 查询?
  • 我想我需要用 PHP 改变结果来获得我的嵌套数组。怎么样?

非常感谢您的帮助:-)

    [0] => Array
    (
        [Post] => Array
            (
                [id] => 1
                [title] => First article
                [content] => aaa
                [created] => 2008-05-18 00:00:00
            )
        [Comment] => Array
            (
                [0] => Array
                    (
                        [id] => 1
                        [post_id] => 1
                        [author] => Daniel
                        [email] => dan@example.com
                        [website] => http://example.com
                        [comment] => First comment
                        [created] => 2008-05-18 00:00:00
                    )
                [1] => Array
                    (
                        [id] => 2
                        [post_id] => 1
                        [author] => Sam
                        [email] => sam@example.net
                        [website] => http://example.net
                        [comment] => Second comment
                        [created] => 2008-05-18 00:00:00
                    )
            )
        [Tag] => Array
            (
                [0] => Array
                    (
                        [id] => 1
                        [name] => Awesome
                    )
                [1] => Array
                    (
                        [id] => 2
                        [name] => Baking
                    )
            )
    )
    [1] => Array
    (
        [Post] => Array
            (...

【问题讨论】:

  • 第一件事:为什么要一个查询?
  • 我们无法在没有数据库架构的情况下为您提供 SQL 查询,因此我们可以查看数据的来源。如果可能的话,这将非常困难,并且将涉及在服务器端对结果数据进行一些解码,这可能(可能会)比仅运行多个查询在计算上更加昂贵。
  • 我已更新问题以反映您的反馈。此外,不需要只使用一个 MySQL 查询。我只是认为那是最好的。欢迎任何具有多个查询的解决方案。

标签: php mysql arrays nested


【解决方案1】:

你最好做 3 个查询。

  1. 首先获取帖子(如果需要,请加入用户),并将它们存储为:

    $list[$row['post_id']]['Post'] = $row;
    
  2. 然后获取所有 post-cmets 并将它们存储为

    $list[$row['post_id']]['Comment'][$row['comment_id']] = $row;
    
  3. 然后获取所有帖子标签

    $list[$row['post_id']]['Tags'][$row['tag_id']] = $row;
    

这比尝试使用单个查询更有效, 作为一个查询,最终会多次发送相同的数据

【讨论】:

  • 可以使用单一查询吗?
  • @RenishKhunt,你从数据库中获得了很多重复的内容,并且必须在 php 中处理它,它速度较慢,而且一团糟。
  • 我也想用一个查询来完成,但是获取所有成员并循环遍历结果效率更高
猜你喜欢
  • 1970-01-01
  • 2016-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-03
  • 2016-11-01
  • 2016-06-07
相关资源
最近更新 更多