2014-01-24 38 views
1

所以,我有2个表:SQL访问优化

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 

将无法​​工作。 如何在不降低速度的情况下将其作为一个查询?

+0

你为什么认为两个查询会明显慢?连接两个表可能比两个简单的表查找花费更多的工作量。 –

+0

我只是在优化我的网站,需要加载太多,我认为数据库请求需要时间从Python传递到实际的数据库。 – RomaValcer

+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子句切碎出来。我很抱歉。

+0

'从defindex = 5719项目中选择名称;'返回项目名称,同时选择items.name,items.imgurl,prices.currency,prices.price 项目 将items添加到items.defindex = prices.defindex 其中items.defindex = 5719和效果= 0和质量= 6;'返回绝对没有。 – RomaValcer

+0

啊坚持下来,我知道它是什么。 –