正如标题所说。我有一个约需2分钟的SQL问题。 SQL问题如下所示:
SELECT *,
(SELECT (CASE WHEN `Grupp_ID` > 0 THEN `Grupp_Name` ELSE `Customers`.`Customer` END) AS `Cust` FROM `Customers` WHERE `Customers`.`ID` = `ordrar`.`CustomerNr`) AS `GruppName`,
(SELECT SUM(REPLACE(`Hours`,',','.')) FROM `anarbetstid` WHERE `order` = `ordrar`.`order`) AS `Hours`,
(SELECT SUM(REPLACE(`Amount`,',','.')) FROM `Resa` WHERE `order` = `ordrar`.`order`) AS `Resor`,
(SELECT COUNT(*) FROM `anmaterial` WHERE `Order` = `ordrar`.`order`) AS `Material`,
(SELECT SUM(REPLACE(`Hours`,',','.') * (SELECT REPLACE(`TimePrice`,',','.') FROM `Arbetstid` WHERE `TimeCode` = `anarbetstid`.`TimeCode`)) FROM `anarbetstid` WHERE `order` = `ordrar`.`order`) AS `TimmarSum`,
(SELECT SUM(REPLACE(`Antal`,',','.') * (SELECT REPLACE(`Price`,',','.') FROM `reselist` WHERE `ID` = `Resa`.`Restyp`)) FROM `Resa` WHERE `order` = `ordrar`.`order`) AS `ResorSum`,
(SELECT CASE `palagg` WHEN 0 THEN SUM((REPLACE(`Rabatt`,',','.') * REPLACE(`Price`,',','.')) * REPLACE(`Amount`,',','.'))
WHEN 1 THEN SUM((REPLACE(`Rabatt`,',','.') * REPLACE(`InPrice`,',','.')) * REPLACE(`Amount`,',','.'))
ELSE 0
END
FROM `anmaterial`
WHERE `Order` = `ordrar`.`order`) AS `MaterialSum`
FROM `ordrar`
WHERE `ordertyp` = '3' group by `ordrar`.`order` ORDER BY `ordrar`.`ID` ASC
如果我删除"按ordrar
分组。order
"我可以让它在大约1分钟内运行。
每张桌子大约有4000行。
有人可以帮助我发现为什么执行此查询需要这么长时间的问题吗?
答案 0 :(得分:0)
为什么不使用LEFT JOIN?我认为这个问题
SELECT *,
(CASE WHEN `Grupp_ID` > 0 THEN `Grupp_Name` ELSE `Customers`.`Customer` END) AS `Cust`
...
LEFT JOIN `Customers` ON `Customers`.`ID` = `ordrar`.`CustomerNr`
...
FROM `ordrar`
WHERE `ordertyp` = '3' group by `ordrar`.`order` ORDER BY `ordrar`.`ID` ASC
答案 1 :(得分:0)
我忘记索引2个表了。这大大减缓了一切。
再次感谢Karthick Kumar!