我有一个复杂的PostgreSQL数据库查询,我在构建时遇到困难。我有两个表:一个post
表和一个votes
表。下面是他们的样子:Postgresql查询在过去24小时内查找排名最高的表格
的post
表 - 我只包括了id
因为其他列不是我的问题很重要
----
| id |
----
的votes
表 - vote_type
可以是1
(给予好评),-1
(downvote)或0
(中性)。 post_id
是单次投票帖子ID的ID。
---- --------- ----------- --------------------------------
| id | post_id | vote_type | timestamp |
---- --------- ----------- --------------------------------
| 1 | 4 | 1 | 2017-03-30 12:17:12.246765-07 |
这里就是我想实现:
SELECT postsTable.*, votesTable.votes
FROM posts AS postsTable
RIGHT JOIN (
SELECT sum(vote_type) votes, post_id
FROM votes
WHERE (extract(day from age(now(), timestamp)) < 1)
GROUP BY post_id)
AS votesTable
ON (postsTable.id = votesTable.post_id)
ORDER BY votes DESC NULLS LAST LIMIT 10;
:过去24小时
我首先构建以下查询中查询前10名得票最多的帖子返回类似于:
---- ---------------------- -------
| id | other_colums_between | votes |
---- ---------------------- -------
| 8 | ... | 1 |
它与正确的帖子略有差异,但是投票栏只显示了过去24小时内的投票总数,而不是自帖子发布以来的总投票数(这正是我想要的)。原因是因为我总结了过去24小时内的投票数,而不是自帖子创建以来的所有投票数。
说post
与id
8有10票。查询只返回1票,因为在过去的24小时内只有一个upvote。
因此,查询应该返回:
---- ---------------------- -------
| id | other_colums_between | votes |
---- ---------------------- -------
| 8 | ... | 10 |
所以我知道我必须解决,但我不知道该怎么做。我已经尝试了下面的查询,但这不是我想要的,但我觉得我正在接近。尽管如此,我还没有在过去24小时内对帖子进行过滤。
SELECT postsTable.*, votesTable.vote_type, extract(day from age(now(), votesTable.timestamp)) age
FROM posts AS postsTable
RIGHT JOIN (SELECT * FROM votes)
AS votesTable ON (postsTable.id = votesTable.post_id)
ORDER BY vote_type DESC NULLS LAST LIMIT 10;
返回:
---- ---------------------- ----------- -----
| id | other_colums_between | vote_type | age |
---- ---------------------- ----------- -----
| 8 | ... | 1 | 3 |
正如你能告诉我在SQL初学者。我还要求提供一些关于如何简化上述查询的建议。感谢您的帮助。
所以,如果我的理解是正确的,你应该摆脱年龄(这其中'WHERE(提取物(现在每天(),时间戳) )<1)' –
要澄清,neutral(0)没有资格作为投票吗? – toonice
是0没有资格作为投票@toonice –