2010-09-15 36 views
0

我正在使用MySQL數據庫。當我執行主表(20 000行)與其他5個表連接的查詢時,需要90秒才能返回結果。然後我在每個條件中添加了索引(where子句)。然後執行時間從90秒下降到45秒,然後我試圖只選擇必要的字段而不是全部(*),這需要25秒。我應該怎麼做才能使它降到不到5秒甚至一秒?如何將MySQL查詢執行時間從90秒減少到少於5秒甚至1秒

SELECT 
ap.propertyid, ap.type_market, 
ap.market_sale_price, ap.sale_from, ap.sale_until, ap.property_salepsf, 
ap.rent_from, ap.property_rent_until, ap.property_rentpsf, ap.title, 
ap.street, ap.suburbs, ap.state, ap.bedrooms, ap.bathrooms, ap.carport, 
ap.buildup_area, ap.builtup_area_from, ap.builtup_area_to, 
ap.land_area, ap.land_area_from, ap.land_area_to, 
ap.status AS prop_status, ap.datecreate AS uploadedOn, type_property.name, (
SELECT name 
FROM gallery 
WHERE 
propertyid = ap.propertyid 
ORDER BY frontpage 
LIMIT 0, 1 
) AS picture, 
uom_mst.uom_shortcode, 
agent_profile.person, agent_profile.mobile, agent_profile.electronicmail, agent_profile.agent_pix, agent_profile.agent_pix_crop, 
country.country_currency_html AS currency, 
owner_profile.oname, owner_profile.omobile, owner_profile.oemail 
FROM agentproperty ap 
LEFT JOIN agent_profile ON (ap.agentid = agent_profile.agentid) 
LEFT JOIN type_property ON (ap.type_property = type_property.rid) 
LEFT JOIN uom_mst ON (ap.property_bua_uom = uom_mst.uom_id) 
LEFT JOIN country ON (ap.property_ctry = country.country_id) 
LEFT JOIN owner_profile ON (ap.propertyid = owner_profile.propertyid) 
WHERE 
ap.status = 'active' AND 
agent_profile.status = 'active' AND 
ap.property_type = '1' AND 
getCompanyID(ap.propertyid) = '001' AND 
ap.agentid = '100010001' 
GROUP BY ap.propertyid 
ORDER BY ap.datecreate DESC 
LIMIT 200, 10 
+0

緩存我的速度。不是一個很好的答案,但這是一個非常大的問題 – WalterJ89 2010-09-15 11:02:07

回答

3

對您的查詢運行EXPLAIN PLAN並查看MySQL對它的說明。

確保JOIN中涉及的所有列都具有與它們關聯的索引。

JOIN中的六個表對於數據庫來說是很多工作。我建議看看重新排序JOIN是否有效。如果您將JOIN從最嚴格的順序排列到最低順序,您可能會減少所需的工作量。

1

假設用的agentId和物業ID(agent_property,agent_profile)和低的選擇性爲狀態,property_types,COUNTRY_ID等具有高選擇性)[這意味着有許多不同agentids和propertyids但很少不同的狀態,屬性類型等]

恕我直言與影響最大的指標是:

  • agent_property(agentid)agent_property(agentid, property_type, status) - 用你的where子句中
  • agent_profile(agentid) - 用於連接
  • owner_profile(propertyid)

但是,你還需要考慮的getCompanyId 的影響,你有沒有考慮到SQL,但它可能會需要至少property(property_id)或任何索引屬性表是。