是的,但是您的子查询需要放在括号中:
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 ."'
您的连接条件将为您执行 case 语句(即 .only 返回i.dPrice
if $priceVal = 1
,并且仅返回 p.dPrice
if $priceVal <> 1
。这避免了在 MySQL 中优化不佳的昂贵子查询。
SQL Fiddle 的简单示例