【问题标题】:MySQL EXISTS() really slowMySQL EXISTS() 真的很慢
【发布时间】:2013-02-22 10:26:44
【问题描述】:

这个查询

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_locations 表中具有位置的项目。

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

【问题讨论】:

  • 你为什么要使用exists?看起来像一个普通的交叉连接(甚至是自然的)会在这里解决问题
  • 项目表primary = itemID; sites_locations 表主自动 AND locationID 是关系;
  • @Najzero 我正在使用 EXISTS() 因为它有效,但我不知道任何其他方法可以让它工作
  • @IanWilkinson 你应该使用INNER JOIN 而不是LEFT JOIN
  • 我不知道为什么这个问题被否决了,但我把它归零了。我也发现 EXISTS 的性能出乎意料的慢。在 Oracle 中,使用 EXISTS 优于使用 DISTINCT 来消除重复。但在 MySQL 中,我发现 DISTINCT 比对给定查询使用 EXISTS 快近 10 倍。

标签: mysql exists


【解决方案1】:

不确定您是否在第二个查询中对表 sites_categories 进行了联接。

【讨论】:

  • 一旦我让它与sites_locations一起工作,我将扩展它以在sites_categories上做同样的事情
【解决方案2】:

INNER JOIN 关键字在两个表中至少有一个匹配项时返回行。

LEFT JOIN 关键字返回左表 (table_name1) 中的所有行,即使右表 (table_name2) 中没有匹配项。

这就是你无法获得价值的区别

Check this link

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-26
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 2010-12-28
    • 2013-01-25
    • 1970-01-01
    • 2012-01-30
    相关资源
    最近更新 更多