SQL访问优化

时间:2014-01-24 17:28:01

标签: sqlite

所以,我有两张桌子:

items (id INTEGER PRIMARY KEY, imgurl text, defindex int, name text),
prices (id INTEGER PRIMARY KEY, defindex int, quality int, effect int, currency text, price real)

如果我需要查找商品的名称,价格和效果名称,我会执行2次查询:

SELECT currency, price from prices where defindex = :def and effect = :eff and quality = :qua
SELECT name, imgurl from items where defindex = :def

我想用1个查询替换它,但问题是有时候没有价格的商品,所以defindex 202存在于商品中,但不存在于价格中,所以

select prices.currency, prices.price, items.name, items.imgurl from items,prices where items.defindex = :def and prices.defindex = :def and prices.quality = :qua and prices.effect = :eff

不行。  如何在不使其变慢的情况下将其整合到一个查询中?

1 个答案:

答案 0 :(得分:1)

它被称为外连接 像这样的东西

Select i.name, i.imgurl, p.currency, p.price 
from items
left join prices on i.defindex = p.defindex
Where i.defindex = :def and effect = :eff and quality = :qua

请注意,这将是所有项目和价格,如果有一个效果和质量。

修订版

Select i.name, i.imgurl, p.currency, p.price 
from items
left join prices p on i.defindex = p.defindex and p.effect =:eff and p.quality = :qua 
Where i.defindex = :def

当没有匹配的价格效果和质量为空时,我原来的尝试中的where子句将其删除。道歉。