1. 两个表,结构如下(以下是mysql脚本,但问题不限于mysql)
CREATE TABLE `author` (
`aid` int(11) NOT NULL auto_increment,
`name` varchar(255) default NULL,
PRIMARY KEY (`aid`)
) TYPE=MyISAM AUTO_INCREMENT=4 ;INSERT INTO `author` VALUES (1, 'tom');
INSERT INTO `author` VALUES (2, 'jack');
INSERT INTO `author` VALUES (3, 'kevin');CREATE TABLE `book` (
`bid` int(11) NOT NULL auto_increment,
`name` varchar(255) default NULL,
`aid` int(11) default NULL,
PRIMARY KEY (`bid`)
) TYPE=MyISAM AUTO_INCREMENT=6 ;INSERT INTO `book` VALUES (1, 'b1', 1);
INSERT INTO `book` VALUES (2, 'b2', 1);
INSERT INTO `book` VALUES (3, 'b3', 1);
INSERT INTO `book` VALUES (4, 'b4', 2);
INSERT INTO `book` VALUES (5, 'b5', 2);其中Author.aid=Book.aid, Author和Book是一对多关系
2. 问题:
现在要查出所有作者及其发表的书籍数量。3. 希望的结果是:
name cnt
-------- ------
tom 3
jack 2
kevin 0我想了一个SQL:
select t1.name, count(*) as cnt from author t1 left join book t2 on t1.aid=t2.aid group by t1.aid
这样出来的结果是
+-------+-----+
| name | cnt |
+-------+-----+
| tom | 3 |
| jack | 2 |
| kevin | 1 |
+-------+-----+
如果通过t1.aid=t2.aid做表关联,那么就不会显示kevin这个作者的信息。

解决方案 »

  1.   

    select t1.name, count(distinct t2.bid) as cnt from author t1 left join book t2 on t1.aid=t2.aid group by t1.aid;
      

  2.   

    select name,sum(num) from 
    (
      select a.aid,a.name ,
      (
        case when bid is null then 0 else 1 end
      ) num from author a left join book b using(aid)
    ) T 
    group by aid;
      

  3.   

    lyg315 的答复能正确得到结果,不过请问为什么要加distinct,我去掉distinct也能得到正确的结果。
      

  4.   

    yueliangdao0608 的sql我在mysql 4.0.12-nt里面执行出错,请问你在哪个数据库里面测试过?