2011-12-08 143 views
0

我想從另一個SELECT內部的相同查詢中獲取信息,但是我不太確定如何獲得我所需的字段。MySQL查詢COUNT輸出

SELECT t.`id`, t.`title`, t.`author`, t.`content`, ctitle, cid, comments 

FROM `tutorials` AS `t`, 

    (
    SELECT tc.`id` as `cid`, tc.`title` as `ctitle` 
    FROM `tutorial_categories` AS `tc` 
    WHERE `title` LIKE '%category title' 
) AS `c`, 

    (
    SELECT COUNT(com.`id`) as `comments` 
    FROM `tutorial_comments` AS `com` 
    WHERE `tutorial_id` = c.cid 
) as `comments` 

WHERE t.`category` = c.`cid` AND t.`status` = '1' 
ORDER BY `id` ASC 

我試圖從tutorial_categories獲取ID和tutorial_comments使用它。所有我想要做的最終輸出是獲得每個教程列出的評論數量。

乾杯,

雅各

回答

2

雅各

您需要通過子句添加一組這樣的

select t.id, t.tilte, t.author, t.content, count(com.id) as comments 
from tutorials as t 
    join tutotials_categories as cat 
     on t.category = cat.id 
    join tutorials_comments as com 
     on com.tutorial_id = t.id 
where cat.title like'%category title' 
    and t.status = 1 
group by com.id 
order by t.id asc 

我用過的在ANSI連接形式

+0

現在只顯示有評論的結果,而不是每個類別的所有結果。 –

+0

我很抱歉,但我沒有明白你的意思。您可以嘗試左連接以顯示那些沒有評論的教程,並且您可以按類別排序以對結果集進行排序。順便說一句,我想你可以嘗試@erwin的腳本。 –

0

你可以試試這個:

SELECT t.`id`, t.`title`, t.`author`, t.`content`, c.title, c.cid, ct.comments 
FROM `tutorials` AS `t` 

LEFT OUTER JOIN (
    SELECT tc.`id` as `cid`, tc.`title` as `ctitle` 
    FROM `tutorial_categories` AS `tc` 
    WHERE `title` LIKE '%category title' 
) AS `c` ON t.`category` = c.`cid` 

LEFT OUTER JOIN (
    SELECT COUNT(com.`id`) as `comments` 
    FROM `tutorial_comments` AS `com` 
    group by com.`id` 
) as `ct` on ct.`tutorial_id` = c.cid 

WHERE t.`status` = '1' 
ORDER BY `id` ASC 
1

這應該清理您的查詢:

SELECT t.id, t.title, t.author, t.content, c.ctitle, c.cid, com.comments 
FROM tutorials AS t 
LEFT JOIN (
    SELECT tutorial_id, COUNT(com.id) as comments 
    FROM tutorial_comments AS com 
    GROUP BY 1 
    ) AS com ON com.tutorial_id = t.category 
LEFT JOIN (
    SELECT tc.id as cid, tc.title as ctitle 
    FROM tutorial_categories AS tc 
    WHERE title LIKE '%category title' 
    ) AS c ON t.category = c.cid 
WHERE t.status = '1' 
ORDER BY t.id 

的LEFT JOIN防止教程消失沒有找到匹配。
我用JOIN條件做了明確的JOIN,這更容易理解,也是正確的方法。
您的主要問題是您的括號內的計數註釋的連接條件,而不是外部,這不能這樣工作。