表1 :table1         
id  name          
1    A             
2    B             
3    C             
4    D   
表1明细表: table1_detail    table1ID  decription  period  amount  
1         PPPP        2008      22 
2         CCCC        2008      33
4         RRRR        2009      44请问怎么样才可以 将表1的所有记录都列出来,而period是等于 2008的  amount数量 ,如果2008无数量显示为0 ? select name,ifnull(amount,0) from  table1 t left join table1_detail tb on t.id=tb.table1ID where tb.period='2008' 
这样写 id=3和 id=4 不会显示 select name,ifnull(amount,0) from  table1 t left join table1_detail tb on t.id=tb.table1ID where tb.period='2008' or tb.period is null
这样写 id=4 会不显示  我要的结果是 name    amount
A       22
B       33
C       0
D       0

解决方案 »

  1.   

    select a.name,ifnull(amount,0)
    from table1 a Left Join (select table1ID,amount FROM  table1_detail Where period='2008' ) b ON a.id=b.table1ID
      

  2.   

    select name,if(period=2008,amount,0) from table1 t  left join table1_detail tb on t.id=tb.table1ID 
      

  3.   

    select name,if(period=2008,amount,0) from table1 t  left join table1_detail tb on t.id=tb.table1ID orselect name,COALESCE(sa,0) from table1 a  left join 
    (select table1ID,sum(amount) as sa from table1_detail where  period='2008' group by table1ID) b
    on a.id=b.table1ID
      

  4.   

    mysql> select name,if(period=2008,amount,0) from table1 a left join table1_detail b on a.id=b.table1id
        -> ;
    +------+--------------------------+
    | name | if(period=2008,amount,0) |
    +------+--------------------------+
    | A    |                       22 |
    | B    |                       33 |
    | C    |                        0 |
    | D    |                        0 |
    +------+--------------------------+
    4 rows in set (0.00 sec)mysql>
      

  5.   


    解释下为什么你会得到这样的结果。
    1:select name,ifnull(amount,0) from table1 t left join table1_detail tb on t.id=tb.table1ID where tb.period='2008' 
    这句话是先查出所有的记录,用左链接的方式,如同SELECT * FROM TABLE1......。得到一个记录集后,再用IFNULL去替换AMOUNT值,然后再把PERIOD=2008的挑出来。第二个问题类似,也是最后去挑选2008的记录,导致查询结果不对。正确的写法在计算AMOUNT值的时候,就带上2008的条件了,而不是结果集生产后,再用2008去选择。