[英]ORDER BY result of SQL query
I have two tables: 我有两个表:
'posts' (where 'post_text' field rows are comments users have posted); “帖子”(其中“ post_text”字段行是用户已发表的评论); and 'votes' (the users' votes (thumbs up/down) on the posts, where 'post_id' matches 'id' from the 'posts' table):
和“投票”(用户对帖子的投票(向上/向下),其中“ post_id”与“ posts”表中的“ 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 |
+----+---------+--------+
What I'd like to do is get all the 'post_text' values from 'posts' table, but sort them by highest no. 我想做的是从“职位”表中获取所有“ post_text”值,但按最高编号对其进行排序。 of thumbs-up ('1') ratings first, then thumbs-downs ('0') to come next, then the posts without ratings (ie no corresponding votes in the 'votes' table) to come last.
首先是(0),然后是没有评级(即“票”表中没有相应的投票)。 With a join, I can achieve this but I don't know how to get the 'post_text' values without ratings to also be in the result.
通过联接,我可以实现此目的,但是我不知道如何在没有评级的情况下获取“ post_text”值。 This is what I got:
这就是我得到的:
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 |
+----+---------+--------+----------+
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.