2011-10-24 74 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 

感谢