代码改变世界

SQL多表查询

2013-09-02 13:52  allbymyself  阅读(475)  评论(0编辑  收藏  举报

MS SQL三表查询:

select Inventory.cInvCode,Inventory.cInvName,max(dDate) from Inventory,SaleBillVouchs,SaleBillVouch
where Inventory.cInvCode = SaleBillVouchs.cInvCode
and SaleBillVouchs.SBVID = SaleBillVouch.SBVID
group by Inventory.cInvCode,Inventory.cInvName
order by Inventory.cInvCode  

 

select Inventory.cInvCode as '存货编码',Inventory.cInvName as '存货名称',convert(char(10),max(dDate),120) as '最后出货日期' from Inventory 
left join SaleBillVouchs
on Inventory.cInvCode = SaleBillVouchs.cInvCode 
left join SaleBillVouch
on SaleBillVouchs.SBVID = SaleBillVouch.SBVID
group by Inventory.cInvCode,Inventory.cInvName
order by Inventory.cInvCode

 

select InventoryClass.cInvCName as '存货分类',
       Inventory.cInvCode as '存货编码',
       Inventory.cInvName as '存货名称',
       CurrentStock.iquantity as '结存数量',
       CurrentStock.foutquantity as '待发货数量',
       CurrentStock.iquantity -CurrentStock.foutquantity as '可用量 ',
       AA_BatchProperty.cBatchProperty1 as '进货价格',
       AA_BatchProperty.cBatchProperty1 * (CurrentStock.iquantity -CurrentStock.foutquantity) as '采购金额',
       convert(char(10),max(dDate),120) as '最后出货日期',
       datediff(day,convert(char(10),max(dDate),120),getdate()) as '呆滞天数'
from Inventory 
left join SaleBillVouchs
on Inventory.cInvCode = SaleBillVouchs.cInvCode 
left join SaleBillVouch
on SaleBillVouchs.SBVID = SaleBillVouch.SBVID
left join CurrentStock 
on Inventory.cInvCode = CurrentStock.cInvCode
left join InventoryClass
on Inventory.cInvCCode = InventoryClass.cInvCCode
left join AA_BatchProperty
on CurrentStock.cBatch = AA_BatchProperty.cBatch and  CurrentStock.cInvCode = AA_BatchProperty.cInvCode
where CurrentStock.iquantity != 0 and InventoryClass.cInvCName != 'MTK'
group by Inventory.cInvCode,Inventory.cInvName,Inventory.cInvCCode,CurrentStock.iquantity,CurrentStock.foutquantity, InventoryClass.cInvCName,AA_BatchProperty.cBatchProperty1
order by Inventory.cInvCode

 

LEFT JOIN 关键字会从左表 (table_name1) 那里返回所有的行,即使在右表 (table_name2) 中没有匹配的行。 

RIGHT JOIN 关键字会右表 (table_name2) 那里返回所有的行,即使在左表 (table_name1) 中没有匹配的行。

 

MySQL:未测试

SELECT * FROM tx1 left join (tx2, tx3) ON (tx1.id=tx2.tid AND tx2.tid=tx3.tid) where tx1.id = 3

 

获取SQL Server日期而不包括时间的方法

http://database.51cto.com/art/201009/228086.htm