2011-10-24 72 views
0

我遇到了以下查詢問題,對於我的iPhone應用程序。當應用程序運行查詢時,需要花費相當長的時間來處理結果,也許大約一秒鐘左右......我想知道查詢是否可以優化嗎?我正在使用FMDB框架來處理我所有的SQL。我的SQL查詢運行緩慢需要優化

select pd.discounttypeid, pd.productdiscountid, pd.quantity, pd.value, p.name, p.price, pi.path 
from productdeals as pd, product as p, productimages as pi 
where pd.productid = 53252 
and pd.discounttypeid == 8769 
and pd.productdiscountid = p.parentproductid 
and pd.productdiscountid = pi.productid 
and pi.type = 362 
order by pd.id 
limit 1 

我的語句是下面的表格:

CREATE TABLE "ProductImages" (
    "ProductID" INTEGER, 
    "Type" INTEGER, 
    "Path" TEXT 
) 

CREATE TABLE "Product" (
    "ProductID" INTEGER PRIMARY KEY, 
    "ParentProductID" INTEGER, 
    "levelType" INTEGER, 
    "SKU" TEXT, 
    "Name" TEXT, 
    "BrandID" INTEGER, 
    "Option1" INTEGER, 
    "Option2" INTEGER, 
    "Option3" INTEGER, 
    "Option4" INTEGER, 
    "Option5" INTEGER, 
    "Price" NUMERIC, 
    "RRP" NUMERIC, 
    "averageRating" INTEGER, 
    "publishedDate" DateTime, 
    "salesLastWeek" INTEGER 
) 

CREATE TABLE "ProductDeals" (
    "ID" INTEGER, 
    "ProductID" INTEGER, 
    "DiscountTypeID" INTEGER, 
    "ProductDiscountID" INTEGER, 
    "Quantity" INTEGER, 
    "Value" INTEGER 
) 

回答

1

你有外鍵列(productimages.productid和product.parentproductid)指標,並使用欄找到合適的產品交易(productdeals.productid和productdeals.discounttypeid)?如果不是,那可能是表現不佳的原因。

你可以這樣創建它們:

CREATE INDEX idx_images_productid ON productimages(productid); 
CREATE INDEX idx_products_parentid ON products(parentproductid); 
CREATE INDEX idx_deals ON productdeals(productid, discounttypeid); 
+0

socha23嗨,我已經加了我的產品和productimages表的語句。你能告訴我我需要做什麼來將外鍵添加到表中嗎? – Peter

+0

我用SQL語句創建索引更新了我的答案,嘗試它們並查看它們是否可以解決問題 – socha23

+0

這看起來工作得更好。我會繼續嘗試不同的查詢來確保。基於我的查詢是否需要所有索引,我還添加了我的productdeals模式?我需要閱讀索引! – Peter

0

下面的查詢可以幫助你減少執行時間,而且儘量正確地創建索引的字段來固定你的查詢。

select pd.discounttypeid, pd.productdiscountid, pd.quantity, pd.value, p.name, 
    p.price, pi.path from productdeals pd join product p on pd.productdiscountid = 
    p.parentproductid join productimages pi on pd.productdiscountid = pi.productid where 
    pd.productid = 53252 and pd.discounttypeid = 8769 and pi.type = 362 order by pd.id 
    limit 1 

感謝