合并来自不同表的两个SELECT查询

时间:2013-08-09 23:02:18

标签: php mysql sql database

问题

我有一个表(posts)包含文章和文章元。

另一个表格(post_reviews)包含每篇文章的用户提交的评分(5分之一的值),并通过相关帖子的posts引用id

我试图通过审核找到过去3天的前三个帖子。因此我需要:

  • 查找该时段(3天)内的所有帖子
  • 找到每篇文章的平均评分
  • 按平均评分(desc)排序

代码

对于第一部分,我可以成功使用查询:

SELECT * FROM `posts` WHERE `hub_id`=:hub_id AND `date`>=:start_date AND `date`<=:end_date)

要查找每个帖子的平均评分,我使用此查询:

SELECT SUM(`review`) AS `total` FROM `post_reviews` WHERE `id`=:id

然后从中获取行数以计算出平均值:

SELECT * FROM `post_reviews` WHERE `post_id`=:id

我如何将这三者合并,或者处理这些数据,以便我可以按照平均评分在一段时间内订购帖子?

ANSWER

最终结果如下:

SELECT   `posts`.`id`, avg(`post_reviews`.`review`) as `average`
FROM     `posts` 
JOIN     `post_reviews` ON (`posts`.`id`=`post_reviews`.`post_id`)
WHERE    `hub_id`=:hub_id
    AND `posts`.`date`>=:start_date
    AND `posts`.`date`<=:end_date
GROUP BY `post_id`
ORDER BY avg(`review`) desc

3 个答案:

答案 0 :(得分:1)

不确定hub_id代表什么,但我认为这是必要的;还假设帖子中的关键字段为posts.post_id而非posts.id

SELECT   `p`.`id`, avg(`pr`.`review`) AS `average`
FROM     `posts`        AS `p`
JOIN     `post_reviews` AS `pr` ON (`p`.`id`=`pr`.`post_id`)
WHERE    `hub_id` =:hub_id
     AND `p`.`date` BETWEEN CURRENT_DATE-3 AND CURRENT_DATE
GROUP BY `p`.`id`
ORDER BY avg(`review`) DESC;

参见示例:sqlfiddle

答案 1 :(得分:0)

不确定MySQL的语法,但需要连接和分组。 像......那样......

SELECT post_id. avg(review)
FROM Posts P Inner Join Post_reviews PR on (p.post_id = pr.Post_id)
WHERE `hub_id`=:hub_id AND `date`>=:start_date AND `date`<=:end_date)
Group by Post_id
order by 2 desc

答案 2 :(得分:0)

这是一个与sqlfiddle一起使用的查询来证明它。

SELECT 
  p.hub_id
 ,p.post_id
 ,p.article
 ,p.articleMeta
 ,p.date
 ,IFNULL(AVG(r.ratings), 0) averageRating
FROM posts p
  LEFT JOIN post_reviews r ON
    r.post_id = p.post_id
WHERE 
    hub_id = 1 
  AND date >= CURDATE() - 3
  AND date <= CURDATE()
GROUP BY 
  p.hub_id
 ,p.post_id
 ,p.article
 ,p.articleMeta
 ,p.date
ORDER BY
  p.date DESC
 ,averageRating DESC

http://sqlfiddle.com/#!2/39315/1