关于SQL多表查询
本帖最后由 lnnweb1 于 2013-03-23 20:11:56 编辑 一,表1名:djb
Number Bopomofo_Ab GoodsName Provider
1 DM 大米 阿里巴巴
2 HD 黄豆 阿里巴巴
3 XM 小麦 阿里巴巴
4 LD 绿豆 阿里巴巴
5 DD 大豆 阿里巴巴
二,表2名:Storage_kc
ID DJBID GoodsName SpecType remarks Quantity CentralUnit
1 1 大米 干货 东北 500 斤
2 3 小麦 干货 东北 1000 斤
3 5 大豆 干货 东北 2000 斤
三,表3名:ck1_ls
ID DJBID KCID GoodsName Quantity_ck CentralUnit
1 3 2 小麦 400 斤
四,通过以上3个表djb,Storage_kc,ck1_ls的关系,如何才能达到以下效果:
ID DJBID GoodsName SpecType remarks Quantity CentralUnit Provider Quantity_ck
1 1 大米 干货 东北 500 斤 阿里巴巴 NULL
2 3 小麦 干货 东北 1000 斤 阿里巴巴 400
3 5 大豆 干货 东北 2000 斤 阿里巴巴 NULL
[解决办法]
select b.*,a.Provider,c.Quantity_ck from djb Storage_kc b
left join djb a on a.Number=b.ID
left join ck1_ls c on b.DJBID = c.DJBID
[解决办法]
--建表
create table djb
(
number int identity not null,
bopomofo_ab varchar(10),
goodsname varchar(20),
provider varchar(20)
);
create table storage_kc
(
id int identity,
djbid int not null,
goodsname varchar(20),
spectype varchar(10),
remarks varchar(10),
quantity int,
centralunit varchar(10)
);
create table ck1_ls
(
id int identity,
djbid int not null,
kcid int not null,
goodsname varchar(20),
quantity_ck int,
centralunit varchar(10)
);
--查询
select temp.id, temp.djbid, temp.goodsname, temp.spectype, temp.remarks ,temp.quantity, temp.centralunit,
a.provider ,
temp.quantity_ck
from djb a join
(
select b.id, b.djbid, b.goodsname, b.spectype, b.remarks ,b.quantity, b.centralunit,
c.quantity_ck
from storage_kc b
left join
ck1_ls c
on b.djbid = c.djbid
)temp
on a.number = temp.djbid;
--结果
iddjbidgoodsnamespectyperemarksquantitycentralunitproviderquantity_ck
11大米干货东北500斤阿里巴巴NULL
23小麦干货东北1000斤阿里巴巴400
35大豆干货东北2000斤阿里巴巴NULL