How to set a default row for a query that returns no rows?

后端 未结 11 1470
青春惊慌失措
青春惊慌失措 2020-12-03 06:43

I need to know how to return a default row if no rows exist in a table. What would be the best way to do this? I\'m only returning a single column from this particular table

11条回答
  •  难免孤独
    2020-12-03 07:16

    Assuming there is a table config with unique index on config_code column:

    CONFIG_CODE     PARAM1   PARAM2
    --------------- -------- --------
    default_config  def      000
    config1         abc      123
    config2         def      456
    

    This query returns line for config1 values, because it exists in the table:

    SELECT *
      FROM (SELECT *
              FROM config
             WHERE config_code = 'config1'
                OR config_code = 'default_config'
             ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END)
     WHERE rownum = 1;
    
    CONFIG_CODE     PARAM1   PARAM2
    --------------- -------- --------
    config1         abc      123
    

    This one returns default record as config3 doesn't exist in the table:

    SELECT *
      FROM (SELECT *
              FROM config
             WHERE config_code = 'config3'
                OR config_code = 'default_config'
             ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END)
     WHERE rownum = 1;
    
    CONFIG_CODE     PARAM1   PARAM2
    --------------- -------- --------
    default_config  def      000
    

    In comparison with other solutions this one queries table config only once.

提交回复
热议问题