2011-12-06 172 views
1

我試圖運行此查詢但它只是輸出有項目在他們,而不是所有的類類別的結果。這是我的查詢:MySQL查詢輸出

SELECT categories.`id` as `cat_id`, categories.`title` as `cat_title`, COUNT(tutorials.`id`) as `total` 
FROM `tutorial_categories` as `categories`, `tutorials` 
WHERE tutorials.`category` = categories.id 
GROUP BY `cat_id` 

任何人都可以帶我在正確的方向嗎?謝謝。

回答

2
SELECT 
categories.id , 
categories.title, 
COUNT(*) as total 
FROM tutorial_categories as categories 
LEFT JOIN tutorials 
on tutorials.category = categories.id 
GROUP BY categories.id 
+0

最佳答案工作。感謝堆! :) –

+0

很高興我能幫助你。 :) –

+0

您將無法指示我如何從'tutorials'表中獲取最新的ID以及每個類別的ID? –

-2

你有WHERE tutorials.類別= categories.id集,因此只會返回滿足條件的行。刪除它,它應該返回「所有類別」。

SELECT categories.`id` as `cat_id`, categories.`title` as `cat_title`, COUNT(tutorials.`id`) as `total` 
FROM `tutorial_categories` as `categories`, `tutorials` 
GROUP BY `cat_id` 
+0

卸下哪裏會導致CARTES伊恩產品數量的結果,它需要一個明確的加入,而不是一個 –

+0

@DanKelly耶我的壞。我在From子句中錯過了。 – Robert

0

您需要使用LEFT JOIN。你的隱式連接語法產生內部聯接insetad:

SELECT 
    categories.`id` as `cat_id`, 
    categories.`title` as `cat_title`, 
    COUNT(tutorials.`id`) as `total` 
FROM 
    `tutorial_categories` `categories` LEFT JOIN `tutorials` ON categories.id = tutorials.category 
GROUP BY `cat_id` 
0

您正在尋找一個外部聯接描述here:「外部聯接不要求每個記錄在兩個連接表有一個匹配的記錄」

0

您需要使用外連接,而不是使用再整查詢的WHERE

像這樣的事情

SELECT categories.`id` as `cat_id`, categories.`title` as `cat_title`, COUNT(tutorials.`id`) as `total` 
FROM `tutorial_categories` as `categories`, `tutorials` 
LEFT OUTER JOIN tutorials.`category` = categories.id 
GROUP BY `cat_id`