有3张表;
表A: AID, AName;主键AID
表B: BID , BName,AID;主键BID
表C: CID,CName,BID ;主键CID
输入:AID
输出:BID,BName,NCountC。
其中NCount为BID所对应CID的个数;语句该怎么写?

解决方案 »

  1.   

    select b.bid,b.bname,count(cid) as NCountCfrom b inner join a on b.aid=a.aid
    inner join c on b.bid=c.bid where a.aid='aid' group by b.bid,b.bname
      

  2.   

    SELECT b.bid, b.bname, COUNT(cid) AS NCountC
    FROM b INNER JOIN
          a ON b.aid = a.aid INNER JOIN
          c ON b.bid = c.bid
    WHERE (a.aid = 'aid')
    GROUP BY b.bid, b.bname
      

  3.   

    select b.BID,b.BName,(case when c.cid is null then 0 else count(cid) end) as NCountC from b left join c on c.bid=b.bid where b.aid='输入:AID'
      

  4.   

    select b.BID,
    b.BName,count(c.cid) as NCountC
    from tb as b left join tc  as c
    on b.bid=c.bid where b.aid=1 group by b.bid,b.bname
      

  5.   

    要A表没用,因为AID为输入的条件,输出的内容不饱含A表的字段,所以没有必要三个表联合取值,只用B表和C表即可