我的SQL查询运行缓慢需要优化

时间:2011-10-24 13:17:55

标签: iphone sqlite fmdb

我的iPhone应用程序遇到以下问题。当应用程序运行查询时,处理结果需要相当长的时间,可能大约一秒左右......我想知道查询是否可以进行优化?我正在使用FMDB框架处理我的所有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
)

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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

由于