2014-01-24 37 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

啊堅持下來,我知道它是什麼。 –