MySQL离开了加入和计数

时间:2011-12-28 14:16:38

标签: php mysql

我的MySQL表中有两个表:cat和notes。

MySQL for cat

CREATE TABLE IF NOT EXISTS `cat` (
  `cat_id` int(11) NOT NULL AUTO_INCREMENT,
  `cname` int(11) NOT NULL,
  PRIMARY KEY (`cat_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

MySQL for notes:

CREATE TABLE IF NOT EXISTS `notes` (
  `notes_id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(50) NOT NULL,
  `notebody` varchar(300) NOT NULL,
  `cat_id` int(20) NOT NULL,
  `approved` int(11) NOT NULL,
  PRIMARY KEY (`notes_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

我想知道如何计算每个类别已批准等于1的笔记数量。我想显示具有零注释的类别作为类别名称 - 0.我尝试了左连接但是它将所有类别保留为零注释。

1 个答案:

答案 0 :(得分:0)

尝试

SELECT cat_id, COUNT(*) AS cnt
FROM notes
WHERE approved = 1
GROUP BY cat_id

SELECT c.cat_id, c.cname, COUNT(*) AS cnt
FROM cat c
LEFT OUTER JOIN notes n ON n.cat_id = c.cat_id
GROUP BY c.cat_id
HAVING cnt < 1
相关问题