left join   左连接——以左边的数据表为基准,若右边的数据表没有对应的数据则显示空白
right join 右连接——以右边的数据表为基准。


<1>select a.* from tb1 a inner join tb2 b on a.id=b.id
符合条件tb1的所有记录选出来
<2> select a.* from tb1 a left join tb2 b on a.id=b.id
将把表tb1的所有记录选出来(不管后面的条件,此时假如不符合条件的b.*是null)
<3>select a.*  from tb1 a left join tb2 b on a.id=b.id and b.id is not null
 和<1>的效果是一样的
注释:tb1就是a,tb2就是b,这都是表名。

 
<1> A INNER JOIN B ON A.c=B.c
表示取出A、B中都包含c的项
<2> A LEFT JOIN B ON A.c=B.c
A中所有项,B中所有包含在A中的项

例子1
在a中有记录,b没有记录的情况下,使查询记录条数不为空呢,就是让这个查询有查询记录,让b.fid1的值为0
select a.fid1,IsNULL(b.fid1 ,0) as fid1
from a left join  b on a.1=b.1

例子2
表结构如下:
MDate      StoreCode  GoodsCode  ToStoreCode  GoodsAmount  GoodsFlag
2005-12-12   001             101                  888                         2            3
2005-12-13   001             101                     3                          1
2005-12-15   001             101                     1                          2

三条记录的意思分别为:
2005-12-12从001移到888  2件        
2005-12-13从001销售     3件
2005-12-15仓店001进货   2件

出报表
StoreCode  GoodsCode  StockAmount   InAmount     OutAmount    SellAmount
001              101                       3                  0                      2             1 
注:StockAmount进货数量   InAmount移入数量     OutAmount移出数量    SellAmount销售数量

select
    StoreCode,
    GoodsCode,
    StockAmount = sum(case GoodsFlag when 2 then GoodsAmount else 0 end),
    InAmount    = sum(case GoodsFlag when 4 then GoodsAmount else 0 end),
    OutAmount   = sum(case GoodsFlag when 3 then GoodsAmount else 0 end),
    SellAmount  = sum(case GoodsFlag when 1 then GoodsAmount else 0 end)
from
    表
group by
    StoreCode,GoodsCode

例子3
po_order_det 表
ID   MA_ID     QTY
01   #21钢     30 
02   #22钢     40
03   #23铝     30

ST_CONVER 表
ID  QTY
01  20
02  10
要求返回集 QTY = po_order_det.QTY - ST_CONVER.QTY AND po_order_det.ID=ST_CONVER.ID

ID     MA_ID   QTY
01     #21钢   10
02     #22钢   30
03     #23铝    30

select a.order_id,a.id,a.ma_id,a.qty,isnull(b.qty,0) qtyy, isnull(a.qty  - b.qty ,0) qtyx
from po_order_det a left join st_conver b
on a.id=b.id and a.filid=b.filid
and a.id=b.id and a.order_id=b.order_id
Where  a.filid='S'


posted on 2006-02-24 18:04  apple  阅读(833)  评论(0编辑  收藏  举报