我有2个sql表
1。类别表
-id
-name
-url
-content
2.Entry表
-id
-title
-content
-cat //category
-view
-author
我想按条目表中的类别总数对所有类别进行排序
我想根据此查询返回的值对类别进行排序:
SELECT count(cat) as catcount,
cat
FROM entry
GROUP BY cat
ORDER BY catcount DESC
此查询当前返回两个结果。我要打印的区域中有20个地方。我想将随机字段写入空白字段
sample data:
kitap
acil
expected data:
kitap
acil
random category.name 18 piece
答案 0 :(得分:1)
您只想要一个left join
吗?
SELECT c.id, COUNT(e.id) as catcount
FROM category c LEFT JOIN
entry e
ON c.id = e.cat
GROUP BY c.id
ORDER BY catcount DESC ;
答案 1 :(得分:0)
更理想的方法是将子查询分组,然后加入字典:
select c.cat_id, c.cat_name, e.cnt
from Categories as c
left join (
select e.cat_id, count(*) as cnt
from Entries as e
group by e.cat_id
) as e
on e.cat_id = c.id
order by e.cnt desc