获取单个条目时获取查询排名

时间:2014-03-21 12:09:01

标签: php mysql wordpress

我正在开发一个你喜欢帖子的项目,其中喜欢存储在表likes中,其中postId引用表$wpdb->posts(wordpress)中帖子的ID。我需要totalLikesrank后者是当前帖子的排名。

这在获取所有帖子时都有效,但当我需要一个帖子时,我将rank设为1,而不是正确的排名,因为查询结果只包含一个条目。

SELECT @curRank := @curRank + 1 AS rank, $wpdb->posts.*, (SELECT COUNT(*) FROM likes l WHERE l.postId = $wpdb->posts.ID) as totalLikes
            FROM $wpdb->posts, (SELECT @curRank := 0) r
            WHERE $wpdb->posts.post_type = 'post'
            AND $wpdb->posts.post_status = 'publish'
            ORDER BY totalLikes DESC

如何在获得单个帖子时获得排名?

1 个答案:

答案 0 :(得分:1)

您需要使用子查询:

SELECT *
FROM (SELECT @curRank := @curRank + 1 AS rank, $wpdb->posts.*,
             (SELECT COUNT(*) FROM likes l WHERE l.postId = $wpdb->posts.ID) as totalLikes
      FROM $wpdb->posts CROSS JOIN (SELECT @curRank := 0) r
      WHERE $wpdb->posts.post_type = 'post' AND $wpdb->posts.post_status = 'publish'
      ORDER BY totalLikes DESC
     ) t
WHERE <whatever condition you want>;

请注意,这确实具有性能影响,因为子查询已实现&#34;。但是,您必须进行排序,这样才能增加额外的开销。