K, so I have two tables:
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 |
+------------------+-------------+
I want t开发者_如何转开发o get all from categories and count the number of questions (question_id) on each category.
Say, the first category, billing, would have 1 question and the second one, security, would have 3 questions.
I've tried this:
SELECT categories.*, count(categories_questions.id) AS numberOfQuestions
FROM categories
INNER JOIN categories_questions
ON categories.id = categories_questions.category_id
You want to do this:
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
The LEFT JOIN
will make sure that categories with no questions get listed with count = 0
This should do it... you just need to aggregate on something before counting:
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
String p_query = "select c.* , count(o.id) from CustomerTable c , OrderTable o where c.id=o.customerId GROUP BY c.id";
Hope this will help you.Thanks
精彩评论