LEFT JOIN性能问题mysql

时间:2014-09-17 03:04:25

标签: mysql sql

此查询正常工作并带来598行:

SELECT pdwspend.`Parent Supplier Name` , pdwspend.`Child Supplier ID` , pdwspend.`Cat     Tree - Cate` , sum( pdwspend.`Spend Value in LC` )
FROM pdwspend
WHERE pdwspend.Version = 'FINAL'
AND pdwspend.YearMonth >= '201310'
AND pdwspend.YearMonth <= '201409'
AND pdwspend.`Excludable` != 'Excluded'
AND pdwspend.`Year` = '2014'
AND pdwspend.`BU ID` = 'BU1'
GROUP BY pdwspend.`Parent Supplier Name` 

我希望在pdwspend时使用ALL EXCEPT。Child Supplier ID = scrubs。BW Parent Number。应该有大约70个匹配,因此,查询应该带来大约528行。这是我的查询:

SELECT pdwspend.`Parent Supplier Name` , pdwspend.`Child Supplier ID` , pdwspend.`Cat Tree - Cate` , sum( pdwspend.`Spend Value in LC` ) 
FROM pdwspend
LEFT JOIN scrubs ON  pdwspend.`Child Supplier ID`  = scrubs.`BW Parent Number`
WHERE pdwspend.Version = 'FINAL'
AND pdwspend.YearMonth >= '201310'
AND pdwspend.YearMonth <= '201409'
AND pdwspend.`Excludable` != 'Excluded'
AND pdwspend.`Year` = '2014'
AND pdwspend.`BU ID` = 'BU1'
AND scrubs.`BW Parent Number` IS NULL 
GROUP BY pdwspend.`Parent Supplier Name`

但mySQL在运行后冻结了。

请指教。

2 个答案:

答案 0 :(得分:1)

尝试使用not exists

SELECT s.`Parent Supplier Name` , s.`Child Supplier ID` , s.`Cat     Tree - Cate` ,
       sum(s.`Spend Value in LC` )
FROM pdwspend s
WHERE s.Version = 'FINAL' AND s.YearMonth >= '201310' AND s.YearMonth <= '201409' AND
      s.`Excludable` <> 'Excluded' AND s.`Year` = '2014' AND s.`BU ID` = 'BU1' AND
      NOT EXISTS (SELECT 1
                  FROM scrubs sc
                  WHERE s.`Child Supplier ID` = sc.`BW Parent Number`
                 )
GROUP BY s.`Parent Supplier Name` ;

为了提高性能,您需要scrubs(BW Parent Number)上的索引。

答案 1 :(得分:0)

如果您只想查看Child Supplier ID = scrubs.BW Parent Number

,您应该使用内部联接
SELECT pdwspend.`Parent Supplier Name` , pdwspend.`Child Supplier ID` , pdwspend.`Cat Tree     - Cate` , sum( pdwspend.`Spend Value in LC` ) 
FROM pdwspend
INNER JOIN scrubs ON  pdwspend.`Child Supplier ID`  = scrubs.`BW Parent Number`
WHERE pdwspend.Version = 'FINAL'
AND pdwspend.YearMonth >= '201310'
AND pdwspend.YearMonth <= '201409'
AND pdwspend.`Excludable` != 'Excluded'
AND pdwspend.`Year` = '2014'
AND pdwspend.`BU ID` = 'BU1'
AND scrubs.`BW Parent Number` IS NULL 
GROUP BY pdwspend.`Parent Supplier Name`

或者你可以尝试使用Child Supplier ID的SUBQUERY USE INDEX并擦洗。BW Parent Number 为了表现出色。