我试图按另一个表(comment_comment)中单个注释的数量对一个表(comment_thread)进行排序。
评论线程
|------------|---------------|
| id | obj_id |
|------------|---------------|
| 1 | 24 |
|------------|---------------|
| 2 | 34 |
|------------|---------------|
评论_评论
|------------|---------------|---------------|
| id | thread_id | des |
|------------|---------------|---------------|
| 1 | 24 | test 1 |
|------------|---------------|---------------|
| 2 | 34 | test 2 |
|------------|---------------|---------------|
| 3 | 34 | test 3 |
|------------|---------------|---------------|
| 4 | 34 | test 4 |
|------------|---------------|---------------|
| 5 | 24 | test 8 |
|------------|---------------|---------------|
所需的输出
|------------|---------------|
| id | obj_id |
|------------|---------------|
| 2 | 34 |
|------------|---------------|
| 1 | 24 |
|------------|---------------|
当前查询
SELECT ctr.obj_id FROM
(SELECT thread_id FROM comment_comment
group by thread_id ORDER BY COUNT(thread_id) DESC) cc
LEFT JOIN comment_thread ctr ON cc.thread_id = ctr.id
查询未按正确的顺序返回comment_comment表。有人可以帮我吗?
真实数据测试:
https://dbfiddle.uk/?rdbms=postgres_9.4&fiddle=7cd9585fd88381818f9581d17fa338f1:
ID 119应该是第一个
答案 0 :(得分:1)
子查询中的ORDER BY
没有(保证)效果。它必须用于最外面的查询。
在ORDER BY
子句中使用相关子查询。
SELECT ct.id,
ct.obj_id
FROM comment_thread ct
ORDER BY (SELECT count(*)
FROM comment_comment cc
WHERE cc.thread_id = ct.obj_id) DESC;
或者通过联接计数左联接聚集和顺序。
SELECT ct.id,
ct.obj_id
FROM comment_thread ct
LEFT JOIN (SELECT cc.thread_id,
count(*) count
FROM comment_comment cc
GROUP BY cc.thread_id) x
ON x.thread_id = ct.obj_id
ORDER BY x.count DESC
NULLS LAST;
答案 1 :(得分:0)
感谢@ sticky-bit,您的解决方案有效,我只是在比较中引用了错误的列。
最终查询
SELECT ct.id,
ct.obj_id
FROM comment_thread ct
LEFT JOIN (SELECT cc.thread_id,
count(*) count
FROM comment_comment cc
GROUP BY cc.thread_id) x
ON x.thread_id = ct.id
ORDER BY x.count DESC
NULLS LAST;