我可以在case语句中使用子查询吗?这可能吗?
这是我的代码:
SELECT SUM(icd.discrepancy * (
CASE WHEN $priceVal = 1
THEN SELECT i.dPrice FROM item_tb i
WHERE i.ID = icd.itemID
ELSE SELECT p.dPrice FROM price_tb p
WHERE p.brID = '". $brID ."' AND p.itemID = icd.itemID
END
)) as total
FROM invcountd_tb icd
WHERE icd.coID = '". $_SESSION['coID'] ."'
AND icd.invCounthID = '". $ID ."'
答案 0 :(得分:0)
是的,你可以但你必须将子查询括在括号e.e:
中CASE WHEN $priceVal = 1 THEN (SELECT i.dPrice FROM item_tb i WHERE i.ID = icd.itemID)
ELSE (SELECT p.dPrice FROM price_tb p WHERE p.brID = '". $brID ."' AND p.itemID = icd.itemID)
END
但是,如果返回多行,您仍然会收到错误
答案 1 :(得分:0)
是的,但您的子查询需要在括号中:
SELECT SUM(icd.discrepancy * (
CASE WHEN $priceVal = 1 THEN
(SELECT i.dPrice FROM item_tb i WHERE i.ID = icd.itemID)
ELSE
(SELECT p.dPrice FROM price_tb p WHERE p.brID = '". $brID ."' AND p.itemID = icd.itemID)
END
)) as total
FROM
invcountd_tb icd
WHERE
icd.coID = '". $_SESSION['coID'] ."'
AND
icd.invCounthID = '". $ID ."'
但我会按如下方式重写:
SELECT SUM(icd.discrepancy * COALESCE(i.dPrice, p.dPrice))
FROM invcountd_tb icd
LEFT JOIN item_tb i
ON i.ID = icd.itemID
AND $priceVal = 1
LEFT JOIN price_tb p
ON p.brID = '". $brID ."'
AND p.itemID = icd.itemID
AND $priceVal <> 1
WHERE icd.coID = '". $_SESSION['coID'] ."'
AND icd.invCounthID = '". $ID ."'
您的加入条件将为您执行案例陈述(即仅i.dPrice
仅返回$priceVal = 1
,如果p.dPrice
仅返回$priceVal <> 1
。这可以避免昂贵的子查询MySQL的优化程度很低。
<强> Simple Example on SQL Fiddle 强>
答案 2 :(得分:0)
要回答您的问题,是的,您可以在Case语句中包含子查询。
此外,在您上面的查询中,我认为您还有另一个问题,即您正在对包含子查询的表达式执行聚合,这会产生错误。