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)。
比方说,第一类,结算,将有1个问题,第二类,安全,将有3个问题。
我试过这个:
SELECT categories.*, count(categories_questions.id) AS numberOfQuestions
FROM categories
INNER JOIN categories_questions
ON categories.id = categories_questions.category_id
答案 0 :(得分:8)
你想这样做:
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
将确保没有问题的类别列在count = 0
答案 1 :(得分:0)
这应该这样做......你只需要在计算之前聚合一些东西:
SELECT categories.*, COUNT(categories_questions.id) AS numberOfQuestions FROM categories
INNER JOIN categories_questions
ON categories.id = categories_questions.category_id
GROUP BY categories.id
答案 2 :(得分:0)
String p_query ="从CustomerTable c,OrderTable o中选择c。*,count(o.id),其中c.id = o.customerId GROUP BY c.id&#34 ;;
希望这会对你有所帮助。谢谢