SELECT行中的子查询

时间:2013-10-17 11:05:08

标签: mysql

我正在尝试使用EVENTSTOCKLINK中的字段生成一个ACTION记录列表(如果存在) 我的查询过去看起来像

SELECT 
  action.actionid,
  partex.stockmake AS partexmake, 
  partex.stockmod AS partexmod
FROM
  ACTION 
  INNER JOIN EVENT 
    ON action.eventid = event.eventid 
  LEFT JOIN 
    (SELECT registrationnumber,stockmake,stockmod,stocktran,eventid 
    FROM eventstocklink 
  LEFT JOIN stock ON stock.stockid = eventstocklink.stockid 
WHERE statusid = '5'
GROUP BY eventstocklink.eventid
) AS partex 
ON partex.eventid = event.eventid 
WHERE actiondate2 BETWEEN 20130601 
  AND 20131031 
  AND event.siteid = 1 
  AND action.typeid = 1 

此查询需要> 4秒 - 所以根据thread的建议,我一直在运行 SELECT行中的子查询,可以通过创建像这样的查询来减少运行时间

SELECT action.actionid,
 (SELECT stockmake FROM eventstocklink
  LEFT JOIN stock ON stock.stockid = eventstocklink.stockid 
  WHERE statusid = '5' AND eventstocklink.eventid = event.eventid
 GROUP BY eventstocklink.eventid) partexmake,
 (SELECT stockmod FROM eventstocklink
  LEFT JOIN stock ON stock.stockid = eventstocklink.stockid 
  WHERE statusid = '5' AND eventstocklink.eventid = event.eventid
 GROUP BY eventstocklink.eventid) partexmod
FROM
  ACTION 
  INNER JOIN EVENT 
    ON action.eventid = event.eventid 
WHERE actiondate2 BETWEEN 20130601 
  AND 20131031 
  AND event.siteid = 1 
  AND action.typeid = 1  

这是构建此查询的最佳方法 - 我想在STOCK表中包含更多字段 有“statusid = 5”的

1 个答案:

答案 0 :(得分:1)

您的新查询具有相关的子查询,这些查询往往表现不佳,而我不确定原始查询中是否需要子查询。

知道表的索引会有所帮助,因为我怀疑这些是你当前查询挣扎的真正原因(例如,eventstocklink.eventid上是否有索引)。

尝试这样的事情: -

SELECT 
  action.actionid,
  MAX(partex.stockmake) AS partexmake, 
  MAX(partex.stockmod) AS partexmod
FROM ACTION 
INNER JOIN EVENT 
ON action.eventid = event.eventid 
LEFT JOIN eventstocklink
ON eventstocklink.eventid = event.eventid
LEFT JOIN stock 
ON stock.stockid = eventstocklink.stockid 
AND stock.statusid = '5'
WHERE actiondate2 BETWEEN 20130601 AND 20131031 
AND event.siteid = 1 
AND action.typeid = 1 
GROUP BY action.actionid

如果存在多个匹配的(因为您的现有查询不会尝试定义返回的那些),这确实假设他们并不是真正困扰哪个stockmake或stockmod被返回。