MySQL检查子查询是否返回NULL,然后替换值

时间:2013-07-09 06:37:25

标签: mysql null subquery ifnull

我有mysql查询,如果子查询没有返回结果或null值,我需要在WHERE子句中替换值。

根据需要运行的价格查询

成功运行

SELECT `prices` FROM `pricing`
WHERE (3 BETWEEN `from_unit` AND `to_unit`)
AND `type` = 1
AND `id_pricing` IN 
    (   
        SELECT v1.`id_pricing` FROM `values` AS v1
        INNER JOIN `values` AS v2 ON v1.`id_pricing` = v2.`id_pricing`
        INNER JOIN `values` AS v3 ON v1.`id_pricing` = v3.`id_pricing`
        INNER JOIN `values` AS v4 ON v1.`id_pricing` = v4.`id_pricing`
        WHERE v1.`id_attribute` = 1 AND v1.`id_value` = 1
        AND v2.`id_attribute` = 7 AND v2.`id_value` = 63
        AND v3.`id_attribute` = 8 AND v3.`id_value` = 87
        AND v4.`id_attribute` = 12 AND v4.`id_value` = 143  
    )

当我按如下所示修改此查询时,在IN子句内的子查询中添加IFNULL检查,它会抛出错误

'SQL错误(1242):子查询返回超过1行'

SELECT `prices` FROM `pricing`
WHERE (3 BETWEEN `from_unit` AND `to_unit`)
AND `type` = 1
AND `id_pricing` IN 
    (   IFNULL  (
                    (   SELECT v1.`id_pricing` FROM `values` AS v1
                        INNER JOIN `values` AS v2 ON v1.`id_pricing` = v2.`id_pricing`
                        INNER JOIN `values` AS v3 ON v1.`id_pricing` = v3.`id_pricing`
                        INNER JOIN `values` AS v4 ON v1.`id_pricing` = v4.`id_pricing`
                        WHERE v1.`id_attribute` = 1 AND v1.`id_value` = 1
                        AND v2.`id_attribute` = 7 AND v2.`id_value` = 63
                        AND v3.`id_attribute` = 8 AND v3.`id_value` = 87
                        AND v4.`id_attribute` = 12 AND v4.`id_value` = 143
                    ),  
                    '1234'
                )
    )

我尝试用COALESCE替换IFNULL仍然是相同的结果。我使用了错误的语法。

1 个答案:

答案 0 :(得分:1)

可能将其移至LEFT JOIN并检查是否有记录,或者定价是1234: -

SELECT `prices` 
FROM `pricing`
LEFT OUTER JOIN
(
    SELECT v1.`id_pricing`, COUNT(*)
    FROM `values` AS v1
    INNER JOIN `values` AS v2 ON v1.`id_pricing` = v2.`id_pricing`
    INNER JOIN `values` AS v3 ON v1.`id_pricing` = v3.`id_pricing`
    INNER JOIN `values` AS v4 ON v1.`id_pricing` = v4.`id_pricing`
    WHERE v1.`id_attribute` = 1 AND v1.`id_value` = 1
    AND v2.`id_attribute` = 7 AND v2.`id_value` = 63
    AND v3.`id_attribute` = 8 AND v3.`id_value` = 87
    AND v4.`id_attribute` = 12 AND v4.`id_value` = 143
    GROUP BY v1.`id_pricing`
) Sub1
ON Sub1.id_pricing = pricing.id_pricing
WHERE (3 BETWEEN `from_unit` AND `to_unit`)
AND `type` = 1
AND (Sub1.`id_pricing` IS NOT NULL
OR pricing.id_pricing = '1234')