根据 table1 的 tb1.id 和 tb2.field 选择 count(tb2.field_name)

selecting count(tb2.field_name) based on tb1.id of the table1 and tb2.field

这个问题以前可能有人问过,但我找不到了。因为我无法正确询问所有情况。如果这是一个重复的问题,请原谅我。 我有 2 个表: tb1 - 类别 tb2 - 任务 我想 select 每个类别的所有任务和任务数量。

我做的是这样的:

SELECT category_id, category_title, 
       (SELECT count(task_id) FROM tasks_of_app WHERE category_id ) AS counted_tasks 
FROM categories_of_app

但我得到了每个类别的所有任务数量。

我不能使用 WHERE 因为没有输入参数。

请各位大侠帮忙看看应该看什么书才能提出这样的疑问。

如果 tasks_of_app 中的列 category_id 引用了 categories_of_app 的列 category_id,那么您需要连接和聚合:

SELECT c.category_id, c.category_title, count(t.task_id) counted_tasks 
FROM categories_of_app c LEFT JOIN tasks_of_app t
ON t.category_id = c.category_id
GROUP BY c.category_id, c.category_title

WHERE category_id 需要指定 category_id 应该是什么。您需要将它与另一个 table 的值相匹配,以使其成为相关子查询。

SELECT category_id, category_title, 
       (SELECT count(task_id) 
        FROM tasks_of_app 
        WHERE tasks_of_app.category_id = categories_of_app.category_id) AS counted_tasks 
FROM categories_of_app

但是更好的写法是 LEFT JOIN 在 table 之间。

SELECT c.category_id, c.category_title, COUNT(t.task_id) AS counted_tasks
FROM categories_of_app AS c
LEFT JOIN tasks_of_app AS t ON c.category_id = t.category_id
GROUP BY c.category_id