MySQL查询COUNT输出

时间:2011-12-08 02:59:04

标签: mysql

我正在尝试从同一查询中的另一个SELECT中获取信息,但是我不太确定如何获取我所需的字段。

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中使用它。我想要做的最后一个输出就是得到每个教程列出的评论数量。

干杯,

雅各

3 个答案:

答案 0 :(得分:2)

雅各

您需要像这样添加group by子句

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连接表单

答案 1 :(得分: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,这更容易理解,也更正确 你的基本问题是你在括号内而不是在外面有计数注释的连接条件,这不能以这种方式工作。

答案 2 :(得分: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