加入两个mysql查询,按第二个结果排序第一个查询

时间:2015-12-03 16:50:38

标签: mysql sql join inner-join

我最初有一个运行第一个查询(发布详细信息)的Web服务,并且在其结果的while循环中,我正在运行第二个查询以检索帖子上的注释数。我需要尝试将两者结合起来,因为现在我不得不按照评论的数量订购网络服务。

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

我不确定如何实现这一目标。我需要制作派生表吗?

我最初的尝试:

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')

3 个答案:

答案 0 :(得分:1)

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

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

这将获得所有帖子以及每篇帖子中的评论数量。

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

建议:JOIN评论表也是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,因此也将检索没有任何注释的报告。