5

我有 mysql 查询,如果子查询没有返回结果或空值,我需要替换 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 仍然是相同的结果。我是否使用了错误的语法。

4

1 回答 1

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')
于 2013-07-09T08:17:03.253 回答