我正在尝试编写查询...
select * from inventoryinfo, purchaseorderiteminfo
where inventoryinfo.qtyinstock < inventoryinfo.minqty
and inventoryinfo.AISTATUS = '1'
and inventoryinfo.category <> 'Noritsu Parts'
and inventoryinfo.itemcode = purchaseorderiteminfo.itemcode
and purchaseorderiteminfo.status = '0'
它返回10个项目
在另一张桌子上,此查询显示了哪些商品的订购方式
select * from purchaseorderiteminfo
where status = '0'
它返回8项
我想加入这两个查询来列出10个项目,所以我有:
select * from inventoryinfo, purchaseorderiteminfo
where inventoryinfo.qtyinstock < inventoryinfo.minqty
and inventoryinfo.AISTATUS = '1'
and inventoryinfo.category <> 'Noritsu Parts'
and inventoryinfo.itemcode = purchaseorderiteminfo.itemcode
and purchaseorderiteminfo.status = '0'
但是,它只显示8个项目,因为其他2个项目没有打开订单的订单。有没有办法获得包含所有10个项目的列表,其中有2个项目在purchaseorderiteminfo表中没有数据?
答案 0 :(得分:2)
您希望在表格之间使用left join
。这将从主表中获取所有行,并从左侧开始匹配。
select * from inventoryinfo
left join purchaseorderiteminfo on inventoryinfo.itemcode = purchaseorderiteminfo.itemcode and purchaseorderiteminfo.status = '0'
where inventoryinfo.qtyinstock < inventoryinfo.minqty
and inventoryinfo.AISTATUS = '1'
and inventoryinfo.category <> 'Noritsu Parts'
您还可以使用表的别名来缩短查询:
select * from inventoryinfo i
left outer join purchaseorderiteminfo p on i.itemcode = p.itemcode and p.status = '0'
where i.qtyinstock < i.minqty
and i.AISTATUS = '1'
and i.category <> 'Noritsu Parts'
另请注意,我替换了旧式隐式连接:
from table1, table2
where table1.key = table2.key
使用ANSI标准SQL-92及更高版本中使用的显式语法:
FROM table1
LEFT [OUTER] JOIN table2 ON table1.key = table2.key
-- the OUTER keyword is optional in many databases.
请参阅Bad habits to kick : using old-style JOINs了解您为何要这样做的原因。