嵌套mysql时的情况

时间:2013-05-30 13:48:21

标签: mysql nested-query

 SELECT    ( CASE 
                        WHEN 1944.0000 >= country_from_price 
                            AND 1944.0000 <= country_to_price
                        THEN ((1944.0000 + ((1944.0000 * country_percentage)/100)))
                            ELSE 1944.0000
                        END 
                        )   
                       FROM `country_markup` 
                       WHERE estatus = '1' 
                       AND country_id REGEXP '[[:<:]]138[[:>:]]'

以上查询返回值增加百分比,但如果条件不是完全填充,则返回NULL。我想要的是如果查询返回NULL值应该返回1944.0000 为此我尝试了下面的代码,但没有取得任何成功

SELECT  IF( (SELECT (CASE 
                        WHEN 1944.0000 >= country_from_price 
                            AND 1944.0000 <= country_to_price
                        THEN ((1944.0000 + ((1944.0000 * country_percentage)/100)))
                            ELSE 1944.0000
                        END 
                        )   as f1
                       FROM `country_markup` 
                       WHERE estatus = '1' 
                       AND country_id REGEXP '[[:<:]]223[[:>:]]') IS NOT NULL, f1  ,1944.0000) as final_price

提前致谢

2 个答案:

答案 0 :(得分:0)

这似乎适用于COALESCE(假设您的原始查询只能返回单个记录):

SELECT COALESCE((
  SELECT    
      CASE WHEN 1944.0000 >= country_from_price AND 1944.0000 <= country_to_price
          THEN ((1944.0000 + ((1944.0000 * country_percentage)/100)))
               ELSE 1944.0000
          END         
  FROM `country_markup` 
  WHERE estatus = '1' 
      AND country_id REGEXP '[[:<:]]138[[:>:]]'), 1944.0000) final_price

您可以将LIMIT 1添加到子查询中,以确保它只在需要时返回单个记录。


以下是使用MAX聚合与COALESCE的替代方法:

  SELECT    
      COALESCE(MAX( CASE WHEN 1944.0000 >= country_from_price AND 1944.0000 <= country_to_price
          THEN ((1944.0000 + ((1944.0000 * country_percentage)/100)))
               ELSE 1944.0000
          END ),1944.0000)    final_price   
  FROM `country_markup` 
  WHERE estatus = '1' 
      AND country_id REGEXP '[[:<:]]138[[:>:]]' 

答案 1 :(得分:0)

您只需要测试表达式中country_percentage不为空:

SELECT    (CASE WHEN 1944.0000 between country_from_price AND country_to_price and
                     country_percentage is not null
                THEN ((1944.0000 + ((1944.0000 * country_percentage)/100)))
                ELSE 1944.0000
            END)   
FROM `country_markup` 
WHERE estatus = '1' AND country_id REGEXP '[[:<:]]138[[:>:]]';

我还将比较逻辑更改为使用between