K,所以我有两个表:
categories +----+----------+ | id | slug | +----+----------+ | 1 | billing | | 2 | security | | 3 | people | | 4 | privacy | | 5 | messages | +----+----------+ categories_questions +------------------+-------------+ | id | question_id | category_id | +------------------+-------------+ | 1 | 1 | 2 | | 2 | 2 | 5 | | 3 | 3 | 2 | | 4 | 4 | 4 | | 5 | 4 | 2 | | 6 | 5 | 4 | +------------------+-------------+
我想从类别中获取所有信息,并计算每个类别中的问题数(question_id)。
假设,第一个类别(计费)将有一个问题,第二个类别(安全)将有3个问题。
我已经试过了:
SELECT categories.*, count(categories_questions.id) AS numberOfQuestions FROM categories INNER JOIN categories_questions ON categories.id = categories_questions.category_id
您想这样做:
SELECT categories.id, max(categories.slug), count(categories_questions.id) AS numberOfQuestions FROM categories LEFT JOIN categories_questions ON categories.id = categories_questions.category_id group by categories.id
在LEFT JOIN将确保没有问题类别获得与数= 0上市
LEFT JOIN