我想按访问次数对类别进行排序
类别有任务,任务有访问权限。我有四张桌子:
1)visits
-id
2)category
-id
3)tasks
-id
-category_id
4)task_visit
-task_id
-visit_id
我现在所拥有的:
按访问排序的任务
SELECT count(task_id) as count, task_id
FROM task_visit
GROUP BY task_id
ORDER BY count DESC;
-join带有任务的类别
SELECT *
FROM categories
JOIN tasks
ON categories.id = tasks.category_id
ORDER BY categories.id;
-try加入具有任务和计数访问的类别(不起作用),下一个按类别汇总
SELECT *
FROM categories
JOIN tasks
ON categories.id = tasks.category_id
ORDER BY categories.id
JOIN
(
SELECT count(task_id) as count, task_id
FROM task_visit
GROUP BY task_id
ORDER BY count
) ON tasks.id = task_visit.task_id;
那么,如何按类别对类别进行排序?
答案 0 :(得分:2)
您只需要在category
,tasks
和task_visit
表之间加入,以及按类别汇总:
SELECT
c.id,
COUNT(tv.visit_id) AS cnt
FROM category c
LEFT JOIN tasks t
ON c.id = t.category_id
LEFT JOIN task_visit tv
ON tv.task_id = t.id
GROUP BY
c.id
ORDER BY cnt DESC;