假设我有两张 table :
文章(文章Id、文章详细信息)
评论(commentId、commentDetail、commentArticle)
我使用 commentArticle =articleId 链接文章和评论表
比方说,我通过此查询获取了文章;
SELECT * FROM articles ORDER BY articleId DESC
结果是;
Array(
[0] => stdClass Object
(
[articleId] => 3
[articleDetail] => The details of article 3
)
[1] => stdClass Object
(
[articleId] => 2
[articleDetail] => The details of article 2
)
[2] => stdClass Object
(
[articleId] => 1
[articleDetail] => The details of article 1
)
...
)
你知道,像往常一样;)
我想只用一个查询来获取文章和评论。我尝试过这个;
SELECT
articles.*,
comments.*
FROM
articles
LEFT JOIN
comments ON comments.commentArticle = articles.articleId
ORDER BY
articles.articleId
DESC
不!它不起作用。我想通过一次查询获取评论和文章,就像这样;
Array(
[0] => stdClass Object
(
[articleId] => 3
[articleDetail] => The details of article 3
[articleComments] => Array(
[0] => stdClass Object
(
[commentId] => 1
[commentDetail] => Details of comment 1
[commentArticle] => 3
)
[1] => stdClass Object
(
[commentId] => 2
[commentDetail] => Details of comment 2
[commentArticle] => 3
)
[2] => stdClass Object
(
[commentId] => 3
[commentDetail] => Details of comment 3
[commentArticle] => 3
)
)
)
[1] => stdClass Object
(
[articleId] => 2
[articleDetail] => The details of article 2
[articleComments] => Array( )
)
[2] => stdClass Object
(
[articleId] => 1
[articleDetail] => The details of article 1
[articleComments] => Array(
[0] => stdClass Object
(
[commentId] => 4
[commentDetail] => Details of comment 4
[commentArticle] => 1
)
[1] => stdClass Object
(
[commentId] => 1
[commentDetail] => Details of comment 5
[commentArticle] => 3
)
)
)
...
)
有没有办法通过单个查询来做到这一点?甚至可能重新排列评论?
谢谢。
最佳答案
您可以选择此选项的唯一方法是始终在每条评论中包含文章信息。 没有办法做你想做的事。您将始终得到具有相同列数的行
关于php - 一个查询中的文章和评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22689336/