按行排序不同的表

时间:2016-04-14 20:43:10

标签: php mysql sql

我的“user_likes”表格包含id(int(10) key), user_id(varchar(15)), post_id(varchar(15)),“user_post”表格包含post_id(int(15) key), user_id(varchar(15)), post_txt(text)

我现在按照ID:

订购帖子
$que_posts = mysql_query("select * from user_post order by user_id DESC");

我想根据每个帖子的喜欢量来订购(即有更多喜欢的帖子将是第一个)。

问题是LIKES在不同的表中。我该怎么办?

编辑 - 我使用sef4eg的答案(有变化)我可以解决它:

"SELECT user_post.*, COUNT(user_likes.post_id) AS like_count
                            FROM user_post LEFT JOIN user_likes 
                            ON user_post.post_id = user_likes.post_id
                            GROUP BY user_post.post_id
                            ORDER BY like_count desc;";

1 个答案:

答案 0 :(得分:1)

现在您的选择中有like_count,以便在需要时显示

SELECT user_post.*, COUNT(user_likes.id) as like_count
FROM user_post 
LEFT JOIN user_likes
ON user_likes.user_id = user_post.user_id AND user_likes.post_id = user_post.post_id
GROUP BY user_post.post_id
ORDER BY like_count DESC