ORDER BY SQL查询的结果

时间:2014-06-25 15:34:36

标签: php sql sorting inner-join

我有两张桌子:

'帖子' (其中' post_text'字段行是用户发布的评论);和 '票' (帖子上的用户'投票(竖起/竖起),其中“post_id”匹配'来自“'帖子”表中的内容:

SELECT *
FROM  `posts` 

+----+-----------+
| id | post_text |
+----+-----------+
|  1 | test0     |
|  2 | test1     |
|  3 | test2     |
|  4 | test3     |
|  5 | test4     |
|  6 | test5     |
|  7 | test6     |
|  8 | test7     |
|  9 | test8     |
| 10 | test9     |
| 11 | test10    |
+----+-----------+

SELECT *
FROM  `votes`

+----+---------+--------+
| id | post_id | rating |
+----+---------+--------+
|  1 |       1 |      1 |
|  2 |       2 |      0 |
|  3 |       4 |      1 |
|  4 |       4 |      1 |
|  5 |       6 |      1 |
|  6 |       6 |      1 |
|  7 |       7 |      0 |
+----+---------+--------+

我想做的是获取所有后期文字'来自'帖子'的值表,但按最高排序排序。首先是大拇指(' 1')评级,然后是下一个大拇指(' 0'),然后是没有评级的帖子(即&#39中没有相应的投票) ;投票'表)最后。通过加入,我可以做到这一点,但我不知道如何获得后期文字'没有评级的值也会出现在结果中。这就是我得到的:

SELECT posts.id, post_id, rating, COUNT( * ) 
FROM posts
INNER JOIN votes ON posts.id = votes.post_id
GROUP BY post_id
ORDER BY rating DESC , COUNT( * ) DESC , post_id DESC 
LIMIT 0 , 30

+----+---------+--------+----------+
| id | post_id | rating | COUNT(*) |
+----+---------+--------+----------+
|  6 |       6 |      1 |        2 |
|  4 |       4 |      1 |        2 |
|  1 |       1 |      1 |        1 |
|  7 |       7 |      0 |        1 |
|  2 |       2 |      0 |        1 |
+----+---------+--------+----------+

1 个答案:

答案 0 :(得分:1)

SELECT posts.id, posts.post_text, post_id, rating, COUNT( * ) 
FROM posts
LEFT JOIN votes ON posts.id = votes.post_id
GROUP BY post_id
ORDER BY rating DESC , COUNT( * ) DESC , post_id DESC 
LIMIT 0 , 30