【问题标题】:Intermediate mySQL Query - join two tables together and limit the results中间 mySQL 查询 - 将两个表连接在一起并限制结果
【发布时间】:2012-09-13 03:09:43
【问题描述】:

这是我的餐桌布置:

Posts
   post_id
   post_votes

Comments
   comment_id
   post_id
   comment_time

我未能创建执行以下操作的查询:

  1. 选择 10 个 帖子 按 post_votes desc 排序
  2. 每个帖子获得 5 cmets

如有必要,我会发布我尝试过的内容。 我只是进入更复杂的查询,非常感谢任何帮助或建议

【问题讨论】:

  • 既然是 PHP,你应该嵌套查询。该任务无需使用JOIN
  • 为什么要在 PHP 中嵌套查询而不是加入?这似乎很落后。
  • 我想我需要使用 JOIN,但我不确定如何为每个“帖子”获取多个 cmets。你知道这些类型的查询有什么好的资源吗?
  • 我认为分组可能有用
  • 啊,我没有阅读“每个帖子获得 5 cmets”部分。 MySQL 不能很好地处理这个问题。正确的窗口函数非常有用。 MSSQL、Oracle 和 PostgreSQL 不会有这个问题。

标签: php mysql


【解决方案1】:

下面将分别按 desc 检索 10 个 post order 和 5 cmets order by desc。

select post_id,post_votes,comment_id,comment_time,
 @rn := CASE WHEN @prev_post_id = post_id THEN @rn + 1 ELSE 1 END AS rn,
        @prev_post_id := post_id from
  (select p.post_id,post_votes,comment_id,comment_time from
  (SELECT post_id,post_votes from posts order by post_votes desc limit 10) p 
   left outer join 
   comments c on p.post_id=c.post_id order by post_id,comment_time desc )m
having rn<=5

SQL FIDDLE HERE(通过 desc 检索 3 个 post order 以及每个 post 分别检索 2 cmets 的测试样本)。

【讨论】:

  • 哇,我有很多关于查询的知识。我将对此进行测试,感谢您的时间和专业知识
猜你喜欢
  • 2013-12-04
  • 1970-01-01
  • 2011-05-16
  • 2014-08-17
  • 1970-01-01
  • 1970-01-01
  • 2011-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多