如果未找到记录,请使用其他查询

时间:2014-02-21 05:07:16

标签: mysql

SELECT 
    GROUP_CONCAT(sub.value) AS DURATION
FROM
    (SELECT 
        TENANT_SETTING_VALUE AS VALUE
    FROM
        MST_SITE_PREFERENCES
    WHERE
        `TENANT_ID` = '{0559cdcb-c63b-4c81-be91-b78Tenant1000' 
    UNION 
    SELECT 
        DEFAULT_SETTING
    FROM
        `GLO_SITE_PREFERENCES` AS VALUE
    WHERE
        `SETTING_ID` = 'ESTIMATED_SAVINGS_DURATION_IN_MONTHS') sub;

上述查询返回的值如

130,50
  • 第一个查询(from MST_SITE_PREFERENCES)位于主表
  • 第二个查询(GLO_SITE_PREFERENCES)位于全局表格上。

这里的要求是如果找不到第二个查询的匹配项,它应该返回第一个值 - 130.如果找到,它应该返回值50.所以查询应该只返回一个值。

2 个答案:

答案 0 :(得分:2)

我认为这个版本可以满足您的需求(虽然我不清楚哪个优先,第一个或第二个查询)。

select value
from ((select TENANT_SETTING_VALUE as value, 1 as which
       from MST_SITE_PREFERENCES
       where `TENANT_ID` = '{0559cdcb-c63b-4c81-be91-b78Tenant1000'
      ) union all
      (select DEFAULT_SETTING, 2 as which
       from `GLO_SITE_PREFERENCES` AS VALUE
       where `SETTING_ID` = 'ESTIMATED_SAVINGS_DURATION_IN_MONTHS'
      ) 
     ) t
order by which
limit 1;

如果优先顺序错误,只需切换which上的值。

您也可以将其表达为:

select TENANT_SETTING_VALUE as value, 1 as which
from MST_SITE_PREFERENCES
where `TENANT_ID` = '{0559cdcb-c63b-4c81-be91-b78Tenant1000'
union all
select DEFAULT_SETTING, 2 as which
from `GLO_SITE_PREFERENCES` AS VALUE
where `SETTING_ID` = 'ESTIMATED_SAVINGS_DURATION_IN_MONTHS' and
       not exists (select TENANT_SETTING_VALUE as value, 1 as which
                   from MST_SITE_PREFERENCES
                   where `TENANT_ID` = '{0559cdcb-c63b-4c81-be91-b78Tenant1000'
                  );

同样在这里,如果优先级错误,则需要重新排列子查询。

答案 1 :(得分:0)

SELECT GROUP_CONCAT(sub.value) AS DURATION
FROM
( case 
  when
  ((SELECT count(TENANT_SETTING_VALUE) AS VALUE 
      FROM MST_SITE_PREFERENCES 
    WHERE `TENANT_ID` = '{0559cdcb-c63b-4c81-be91-b78Tenant1000')>0)
  then
    SELECT TENANT_SETTING_VALUE AS VALUE 
      FROM MST_SITE_PREFERENCES 
    WHERE `TENANT_ID` = '{0559cdcb-c63b-4c81-be91-b78Tenant1000')
  when
  ((SELECT count(DEFAULT_SETTING) AS VALUE
    FROM `GLO_SITE_PREFERENCES` 
     WHERE `SETTING_ID`='ESTIMATED_SAVINGS_DURATION_IN_MONTHS')>0)
   then
    SELECT DEFAULT_SETTING AS VALUE
    FROM `GLO_SITE_PREFERENCES` 
     WHERE `SETTING_ID`='ESTIMATED_SAVINGS_DURATION_IN_MONTHS'
) sub;

这项工作提供了subquery returns just 1 row