0

我可以在 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 ."'
4

3 回答 3

1

是的,您可以,但您必须将子查询括在括号 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

但是,如果返回多于一行,您仍然会收到错误

于 2013-10-29T09:11:45.040 回答
0

要回答您的问题,是的,您可以在 Case 语句中使用子查询。

此外,在您上面的查询中,我认为您还有另一个问题,即您正在对包含子查询的表达式执行聚合,这会产生错误。

于 2013-10-29T09:19:25.000 回答
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 ."'

您的连接条件将为您执行 case 语句(即 .only 返回i.dPriceif $priceVal = 1,并且仅返回 p.dPriceif $priceVal <> 1。这避免了在 MySQL 中优化不佳的昂贵子查询。

SQL Fiddle 的简单示例

于 2013-10-29T09:11:52.117 回答