我正在尝试优化此选择,因为在CASE中有相同的选择两次,查询需要两次这么长时间才能运行:
SELECT sc.ID,
(CASE WHEN (SELECT SUM(scu.OK)
FROM `SCU` scu
WHERE scu.ID = _ID
AND scu.CCC = sc.ID
GROUP BY scu.ISC)
IS NULL THEN 0 ELSE
(SELECT SUM(scu.OK)
FROM `SCU` scu
WHERE scu.ID = _ID
AND scu.CCC = sc.ID
GROUP BY scu.ISC)
END )as 'STATUS'
FROM ( SELECT `ID`
FROM `STORE`
WHERE `STATE`=1
ORDER BY `NUMBERIN` DESC) sc
GROUP BY sc.ID;
我试过这样的事情
SELECT sc.ID,
@STATUS:=(SELECT SUM(scu.OK)
FROM `SCU` scu
WHERE scu.ID = _ID
AND scu.CCC = sc.ID
GROUP BY scu.ISC),
(CASE WHEN @STATUS
IS NULL THEN 0 ELSE @STATUS
END ) as 'STATUS'
FROM ( SELECT `ID`
FROM `STORE`
WHERE `STATE`=1
ORDER BY `NUMBERIN` DESC) sc
GROUP BY sc.ID;
但它返回了另一个包含 @STATUS 变量的列,但它不应该。 结果应具有ID和STATUS列。好吗?
答案 0 :(得分:0)
最简单的事情是COALESCE - 可以用来替换具有特定值的NULL。
SELECT sc.ID,
COALESCE((SELECT SUM(scu.OK)
FROM `SCU` scu
WHERE scu.ID = _ID
AND scu.CCC = sc.ID
GROUP BY scu.ISC),0) as 'STATUS'
FROM ( SELECT `ID`
FROM `STORE`
WHERE `STATE`=1
ORDER BY `NUMBERIN` DESC) sc
GROUP BY sc.ID;
答案 1 :(得分:0)
我认为您可以使用IFNULL
执行以下操作:
SELECT sc.ID,
IFNULL(@STATUS:=(SELECT SUM(scu.OK)
FROM `SCU` scu
WHERE scu.ID = _ID
AND scu.CCC = sc.ID
GROUP BY scu.ISC),0,@STATUS) AS `STATUS`
FROM ( SELECT `ID`
FROM `STORE`
WHERE `STATE`=1
ORDER BY `NUMBERIN` DESC) sc
GROUP BY sc.ID;
答案 2 :(得分:0)
这个怎么样?
Select
id,
(CASE WHEN status
IS NULL THEN 0 ELSE status
END ) as 'STATUS'
from
(SELECT sc.ID,
(SELECT SUM(scu.OK)
FROM `SCU` scu
WHERE scu.ID = _ID
AND scu.CCC = sc.ID
GROUP BY scu.ISC) as status
FROM ( SELECT `ID`
FROM `STORE`
WHERE `STATE`=1
ORDER BY `NUMBERIN` DESC) sc
GROUP BY sc.ID) temp
抱歉,我在智能手机中输入了它们。 希望它有所帮助