Can I use a subquery inside a case statement? Is this possible?
Here's my code:
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 ."'
Yes you can but you have to enclose the sub query in parentheses ee:
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
However you can still get errors if there are more than one row returned
Yes, but your subqueries need to be in parentheses:
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 ."'
I would however rewrite this as follows:
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 ."'
Your join conditions will do the case statement for you (ie .only return i.dPrice
if $priceVal = 1
, and only return p.dPrice
if $priceVal <> 1
. This avoids expensive subqueries which are poorly optimised in MySQL.
To answer your question, Yes, you can have a subquery inside a Case statement.
Moreover, in your query above, I think you have another issue, which is that you are performing an aggregation on an expression containing a subquery, which gives an error.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.