加入两个 mysql 查询以根据第二个查询的结果对第一个查询进行排序

join two mysql queries to order the first query by the result of the second

我最初有一个 Web 服务,其中 运行 第一个查询(post 详细信息)并且在其结果的 while 循环中,我是 运行 第二个查询来检索post 上的评论数。我需要尝试将两者结合起来,因为现在我必须按评论数量来订购网络服务。

1. SELECT ReportID, Title, Description, posts.Pic, DatePosted, posts.UserID, FName, SName, users.Pic as userPic, 
                photoWidth, photoHeight
                FROM posts
                INNER JOIN Users 
                ON Users.UserID = posts.UserID 
                WHERE private = 0
                ORDER BY ReportID Desc
                LIMIT ?, 10

2. SELECT COUNT(ReportID) as numComments FROM Comments WHERE ReportID =? AND Comment IS NOT NULL

我不确定如何实现。我需要制作派生的 table 吗?

我的初步尝试:

SELECT ReportID, Title, Description, posts.Pic, DatePosted, posts.UserID, FName, SName, users.Pic as userPic, 
                photoWidth, photoHeight, numComments 
                FROM posts
                INNER JOIN Users 
                ON Users.UserID = posts.UserID 
                WHERE private = 0 AND numComments = (SELECT COUNT(ReportID) as numComments FROM Comments WHERE ReportID = ReportID AND Comment IS NOT NULL)
                ORDER BY numComments DESC

这给出了字段列表中未知列 numComments 的问题

帖子:

- ReportID (primary)
- Title
- Description
- Pic
- private
- DatePosted (epoch)
- photoWidth
- photoHeight

评论:

- CommentID (primary)
- UserID
- ReportID (linking key)
- Comment (can be null if type = 'like')
- dateposted (epoch)
- type ('comment' or 'like')

我没有数据结构,但我认为你可以使用它,在子查询中使用计数

SELECT 
ReportID, Title, Description, posts.Pic, DatePosted, posts.UserID, FName, SName, users.Pic as userPic, 
                photoWidth, photoHeight, numComments.numComments 
                FROM posts
                INNER JOIN Users 
                ON Users.UserID = posts.UserID 
            WHERE private = 0 AND ReportID = (SELECT COUNT(ReportID) as numComments FROM Comments WHERE AND Comment IS NOT NULL GROUP BY ReportID) numComments
            ORDER BY numComments DESC

建议:JOIN评论table也GROUP BY就可以了。

SELECT ReportID, Title, Description, posts.Pic, DatePosted, posts.UserID, 
      FName, SName, users.Pic as userPic, photoWidth, photoHeight, 
      COUNT(CommentID) AS numComments
    FROM posts
    INNER JOIN Users ON Users.UserID = posts.UserID 
    LEFT JOIN Comments ON Comments.ReportID = posts.UserID 
    WHERE private = 0
    GROUP BY Comments.ReportID
    ORDER BY numComments DESC
    LIMIT ?, 10 

编辑:将第二个 JOIN 更改为左 LEFT JOIN,因此也将检索没有任何评论的报告。

如果我正确理解你的问题,我认为你想要的是以下内容:

SELECT Posts.*, count(Comments.ReportID) as CommentCount FROM Posts 
LEFT JOIN Comments
ON Comments.ReportID = Posts.ReportID
WHERE private = 0
GROUP BY Comments.ReportID
ORDER BY CommentCount, ReportID Desc;

显然,您需要调整它以包含您想要的所有字段以及您想要执行的任何其他联接。

这里是demo.

这将获取所有 post 以及每个 post 中的评论数。