我如何只用一个查询而不是这个查询得到结果:
SELECT SUM(`quantity`) as type0 FROM `fruits_delivery`
WHERE `fid`='1001' AND `type`=0;
result_1 = type0;
SELECT SUM(`quantity`) as type1 FROM `fruits_delivery`
WHERE `fid`='1001' AND `type`=1;
result_2 = type1;
final_result = result_1 - result_2;
答案 0 :(得分:9)
你应该使用这个
SELECT sum(IF(`type`=0, `quantity`, 0))-sum(IF(`type`=1, `quantity`, 0))
AS `final_result`
FROM `fruits_delivery`
WHERE `fid` = '1001'
SELECT T1.result - T2.result AS `final_result`
FROM (SELECT Sum(`quantity`) AS result,
`fid`
FROM `fruits_delivery`
WHERE `fid` = '1001'
AND `type` = 0
LIMIT 1) AS T1
JOIN (SELECT Sum(`quantity`) AS result,
`fid`
FROM `fruits_delivery`
WHERE `fid` = '1001'
AND `type` = 1
LIMIT 1) AS T2
ON ( T1.fid = T2.fid )
答案 1 :(得分:9)
或者,您也可以使用CASE
SELECT SUM(CASE WHEN type = 0 THEN quantity ELSE 0 END) -
SUM(CASE WHEN type = 1 THEN quantity ELSE 0 END)
AS final_result
FROM fruits_delivery
WHERE fid = '1001'