這個查詢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
爲什麼要使用在所有的存在?看起來像一個普通的交叉連接(即使是天生的)會在這裏排序 – Najzero 2013-02-22 10:28:10
你的索引是什麼? – h2ooooooo 2013-02-22 10:28:10
items table primary = itemID; sites_locations表中的主要auto和locationID是關係; – 2013-02-22 10:32:53