2011-05-12 61 views
3

ķ算的,所以我有兩個表:獲取所有從另一個

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 

回答

5

你想這樣做:

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

+0

謝謝,我想要沒有任何問題的所有類別。 – weare1 2011-05-12 20:52:40

+0

很高興幫助。讓我們知道它是如何去的。 – 2011-05-12 20:54:48

+0

它工作完美。 – weare1 2011-05-12 20:59:07

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 
0

String p_query =「從CustomerTable c,OrderTable中選擇c。*,count(o.id)o其中c.id = o.customerId GROUP BY c.id」;

希望這會幫助你。謝謝