When using SELECT can you modify the value of a returned field based on other fields?

后端 未结 4 1777
梦毁少年i
梦毁少年i 2021-01-18 02:44

When using MySQL SELECT can you change the value of a returned field based on other fields?

For example, if I have this select:

SELECT city,state,cou         


        
相关标签:
4条回答
  • 2021-01-18 03:14

    Update(misprints corrected):

    SELECT city,state,
    CASE 
     WHEN (city IS NULL OR city='') AND (state IS NULL or state='') THEN ''
     ELSE country
    END as country_1
     FROM `table`
    

    You can also use IF instead of CASE:
    IF ((city IS NULL OR city='') AND (state IS NULL or state=''),'',country) as country_1

    0 讨论(0)
  • 2021-01-18 03:17

    The answer is yes; you're looking for what's called control flow functions.

    Take a look at http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html

    0 讨论(0)
  • Why don't you just use a WHERE clause?

    For example:

    SELECT city, state, country FROM <table> WHERE (city <> "" OR state <> "");
    

    N.B.: You'll need to replace the '<> ""' above with 'IS NOT NULL' if these are actually nulled rather than simply empty.

    0 讨论(0)
  • 2021-01-18 03:36

    a1ex07 is right, but you need to fix a few query errors in his SELECT stmt.

    first, there is a missing comma after "state" and second, if your table were really called "table" you have to enclose in backticks because it is a reserved MySQL keyword.

    SELECT city,state, 
    CASE 
     WHEN (city IS NULL OR city='') AND (state IS NULL or state='') THEN ''
     ELSE country
    END as country_1
     FROM `table`` 
    

    (exlude second backtick, stackoverflow uses those for syntax highlighting if single.)

    0 讨论(0)
提交回复
热议问题