出于某种原因,我将帖子表与评论混合在一起....所以这是comment_of=0
的帖子和comment_of= (number of a post)
的评论
帖子
id_post | id_poster | comment_of | post
23 3 0 hi
24 4 0 hello
25 5 0 how are you
26 3 25 lets go
27 3 24 come on
28 4 25 haha
29 3 25 go away
30 2 24 aint funny
31 3 23 lol
32 3 0 ok
35 3 0 here we go
现在我想要的是按照它有comments.comment_of
的数量订购帖子。 DESC。
MySql 像这样的东西
SELECT post
FROM posts
WHERE comment_of=0
ORDER BY (number of `comment of`) DESC
我期待的是这样的事情
id_post | id_poster | comment_of | post
25 5 0 hi (3 comments)
24 4 0 hello (2 comments)
23 3 0 how are you (1 comment)
32 3 0 ok (0 comments)
35 3 0 here we go (0 comments)
答案 0 :(得分:1)
您可以在order by
中使用子查询:
SELECT p.post
FROM posts p
WHERE p.comment_of = 0
ORDER BY (SELECT COUNT(*) FROM posts p2 WHERE p2.comment_of = p.id_post) DESC;
答案 1 :(得分:1)
您可以LEFT JOIN
在同一个表格和id_post
上进行SELECT p.*, count(p2.id_post) as num
from posts p
left join posts p2 on p2.comment_of = p.id_post
where p.comment_of = 0
group by p.id_post
order by num desc;
,并获取计数:
+---------+-----------+------------+--------------+-----+
| id_post | id_poster | comment_of | post | num |
+---------+-----------+------------+--------------+-----+
| 25 | 5 | 0 | how are you | 3 |
| 24 | 4 | 0 | hello | 2 |
| 23 | 3 | 0 | hi | 1 |
| 35 | 3 | 0 | here we go | 0 |
| 32 | 3 | 0 | ok | 0 |
+---------+-----------+------------+--------------+-----+
输出:
sqlqry1 = "INSERT INTO Timesheet ([StrEMPId]) VALUES (" & TmpEmpId & ");"