2013-05-21 9 views
0

我有一個基於MySQL視圖的記錄集,我用它來返回搜索結果,但它很痛苦緩慢(持續21秒!)。在相同的環境中進行類似的搜索需要一秒鐘的時間。搜索查詢速度慢,基於視圖的記錄集。如何加快速度?

我擔心這是放慢速度的觀點,因爲我在那裏有四個左連接和一個子查詢,以便在搜索中提供相關數據。

在使用視圖時,是否有任何加速查詢的一般指導?我研究了索引,但似乎在MySQL中不允許在視圖中使用。

在此先感謝您的任何建議。

代碼來創建我的觀點:

CREATE VIEW vproducts2 AS 
SELECT products2.productid, products2.active, products2.brandid, 
    products2.createddate, products2.description, products2.inventorynum, 
    products2.onhold, products2.price, products2.refmodnum, products2.retail, 
    products2.sefurl, products2.series, products2.sold, 
    `producttype`.`type` AS type, categories.category AS category, 
    `watchbrands`.`brand` AS brand, productfeatures.productfeaturevalue AS size, 
    (SELECT productimages.image 
     FROM productimages 
     WHERE productimages.productid = products2.productid 
     LIMIT 1 
    ) AS pimage 
FROM products2 
    LEFT JOIN producttype ON producttype.typeid = products2.typeid 
    LEFT JOIN categories ON categories.categoryid = products2.categoryid 
    LEFT JOIN watchbrands ON watchbrands.brandid = products2.brandid 
    LEFT JOIN productfeatures ON productfeatures.productid = products2.productid 
     AND productfeatures.featureid = 1 
+0

我們可以看看您的查詢嗎? –

+0

MySQL認爲這不是一件好事 - 重新考慮重寫你的應用程序並刪除所有可能的視圖。我已經嘗試了幾乎everthing,發現Google也加速了我的應用,並採用了這個激進和高效的解決方案 –

+1

您想要優化參與您視圖的索引。您不能將索引添加到視圖,但可以將視圖添加到基於視圖的基礎表。 – Orangepill

回答

0

你需要確保你對底層表的索引,而不是在視圖。該視圖應該使用這樣的表格。

尖叫出來的第一個索引是productimages(productid, productimage)。這將加速select子句中的子查詢。

您還應該擁有主鍵索引,以便在所有表上看起來像主鍵。 。 。 categories(categoryid),producttype(typeid),watchbrands(brandid),和(我認爲)productfeatures(productid,featureid)。

+0

非常感謝您在回覆中的特異性。我在產品表中創建了索引,沒有明顯的差異。我將通過phpMyAdmin控制檯爲其他相關字段創建索引。我認爲索引字段在控制檯中是可見的,但是在我的主機的控制檯的最新版本中,我沒有看到索引字段。 – Roland

+0

哇 - 一個小索引會有什麼不同!我試圖找出對視圖的索引,但在相關表上進行搜索從21秒到1秒。現在一切正常。感謝所有花時間來和我合作的嘉賓提供具體的指導,讓我確信哪些領域需要索引。 – Roland