2013-02-22 317 views
1

這個查詢MySQL的EXISTS()很慢

SELECT 
    itemID, 
    locationParentID, 
    locationID, 
    categoryParentID, 
    categoryID, 
    itemTitle, 
    itemDetails, 
    itemAttributes, 
    itemPictures, 
    itemFeatured, 
    itemSpotlight, 
    itemAdded 
FROM items 
WHERE items.siteID IN('".$cfg['site']['siteShares']."') 
    AND EXISTS(SELECT 1 FROM sites_locations sl WHERE items.locationID = sl.locationID AND siteID = '".$cfg['site']['siteID']."' LIMIT 1) 
    AND EXISTS(SELECT 1 FROM sites_categories sc WHERE items.categoryID = sc.categoryID AND siteID = '".$cfg['site']['siteID']."' LIMIT 1) 
    AND itemStatus = '1' 
    AND itemAdded > '".$cfg['timestamp']."' 

的作品,但它需要高達6秒

因爲我猜它會更快,我可以用JOIN

這裏就是我嘗試過JOIN,但它會返回所有結果,而不僅僅是在sites_location表中具有位置的項目。

SELECT 
    itemID, 
    locationParentID, 
    categoryParentID, 
    categoryID, 
    itemTitle, 
    itemDetails, 
    itemAttributes, 
    itemPictures, 
    itemFeatured, 
    itemSpotlight, 
    itemAdded 
FROM items LEFT JOIN sites_locations 
    ON items.locationID = sites_locations.locationID 
    AND sites_locations.siteID = items.siteID 
WHERE items.siteID IN('1,2') AND itemStatus = '1' 
    AND itemAdded > '1356048000' ORDER BY itemID DESC LIMIT 15 
+2

爲什麼要使用在所有的存在?看起來像一個普通的交叉連接(即使是天生的)會在這裏排序 – Najzero 2013-02-22 10:28:10

+0

你的索引是什麼? – h2ooooooo 2013-02-22 10:28:10

+0

items table primary = itemID; sites_locations表中的主要auto和locationID是關係; – 2013-02-22 10:32:53

回答

0

不知道,如果你做對錶的連接在第二查詢sites_categories

+0

一旦我得到它與sites_locations一起工作,我會擴展它在sites_categories上執行相同的操作 – 2013-02-22 10:35:36

0

當兩個表中至少有一個匹配項時,INNER JOIN關鍵字將返回行。

LEFT JOIN關鍵字返回左表(table_name1)中的所有行,即使右表(table_name2)中沒有匹配項也是如此。

這就是區別,爲什麼你不能獲取值

Check this link