获得热门帖子

时间:2011-08-07 06:24:35

标签: php mysql

表: 帖子     (ID     标题     数据     用户ID)

连接(     帖子ID     用户ID)

我想通过在CONENCTIONS c表中相同的c.postid值来从POSTS表中获取行

从简单的角度来说,我想获得最热门的帖子,连接最多。

我希望这是有道理的。

4 个答案:

答案 0 :(得分:0)

要从connections表中获取最大值,请尝试以下操作:

SELECT MAX(postid) FROM userid

对其余部分不太确定,但这会在表postid中为您提供userid的最高价值。

答案 1 :(得分:0)

将50替换为您想要获得的热门帖子数量:

select * from post where postid in (
select postid from (
select count(*),postid from connections group by postid order by count(*) desc limit 50 ))

答案 2 :(得分:0)

我还没有测试过,但尝试这样的事情。 它会按照大多数连接的顺序将帖子连接到连接。 (您可以根据您的要求调整限制)

select posts.id, posts.title, posts.data, posts.userid, COUNT(connections.postid) AS total
from posts join connections on posts.id=connections.postid
order by total desc
limit 20

答案 3 :(得分:0)

SELECT p.id, p.name, c.cnt from posts p INNER JOIN (
    SELECT postid, count(*) as cnt 
    FROM connections 
    GROUP BY postid ORDER BY cnt DESC /*limit goes here if you need it!*/) c 
ON c.postid = p.id

一点警告:

如果您处理高负载,那将是非常繁重的查询。我建议你的cnt表中有posts(多个连接)字段(这将是一个非规范化,并且它很难维护,但是可以很好地减少查询时间如果要在index字段上创建cnt,则为2次或更多次。

如果查询有效,请告诉我,因为我现在无法检查自己。