如何用sum连接几个表

时间:2017-12-27 02:22:15

标签: php mysql sql database join

我想按访问次数对类别进行排序

类别有任务,任务有访问权限。我有四张桌子:

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;

那么,如何按类别对类别进行排序?

1 个答案:

答案 0 :(得分:2)

您只需要在categorytaskstask_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;