0

I have two tables.

table1

    aid   alphabet      Name
    1        A          Apple
    2        A          Air
    3        B          Ball
    4        C          Cat
    5        C          Cow
    6        F          Footbal
    7        G          God          

table2

    did    aid    typeId   groupId   description  
    1       1      3         4        apple description
    2       2      3         4        ffdadfdfd
    3       3      5         6        fdsfsdafasdf

I need to select table2 mapping count of each alphabet with a condition typeId 3 and groupId 4.

I wrote this kind of a query but its not fetching all alphabet. Those alphabet have mapping that only its fetching.

select a.alphabet, count(did) from table1 a left join table2 b on a.aid=b.aid where b.typeId=3 and b.groupId=4 group by a.alphabet

How can I write that kind of a query?

I need this kind of an output.

    alphabet   Count
     A          2
     B          0
     C          0
     F          0 .. etc
   
4

1 回答 1

1

By adding the typeId and groupId checks in the where clause, you are effectively making your left join into an inner join, by requiring all rows have values in this joined table. However, this is not the case here. If you move the type and group checks to the on clause (in the join), you should get the desired result.

select
   a.alphabet,
   count(b.did)
from
   table1 a
   left join table2 b 
      on a.aid=b.aid and b.typeId=3 and b.groupId=4
group by
   a.alphabet
于 2011-11-10T06:04:51.337 回答