我正在开发一个你喜欢帖子的项目,其中喜欢存储在表likes
中,其中postId引用表$wpdb->posts
(wordpress)中帖子的ID。我需要totalLikes
,rank
后者是当前帖子的排名。
这在获取所有帖子时都有效,但当我需要一个帖子时,我将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
如何在获得单个帖子时获得排名?
答案 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;。但是,您必须进行排序,这样才能增加额外的开销。