2013-02-22 318 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