MySQL equivalent of DECODE function in Oracle

后端 未结 8 2346
南方客
南方客 2020-11-29 09:26

I am trying to find an equivalent of DECODE function in MySQL. It works like this:

Select Name, DECODE(Age,
       13,\'Thirteen\',14,\'Fourteen\',15,\'Fifte         


        
8条回答
  •  一向
    一向 (楼主)
    2020-11-29 09:29

    Another MySQL option that may look more like Oracle's DECODE is a combination of FIELD and ELT. In the code that follows, FIELD() returns the argument list position of the string that matches Age. ELT() returns the string from ELTs argument list at the position provided by FIELD(). For example, if Age is 14, FIELD(Age, ...) returns 2 because 14 is the 2nd argument of FIELD (not counting Age). Then, ELT(2, ...) returns 'Fourteen', which is the 2nd argument of ELT (not counting the FIELD() argument). IFNULL returns the default AgeBracket if no match to Age is found in the list.

    Select Name, IFNULL(ELT(FIELD(Age,
           13, 14, 15, 16, 17, 18, 19),'Thirteen','Fourteen','Fifteen','Sixteen',
           'Seventeen','Eighteen','Nineteen'),
           'Adult') AS AgeBracket
    FROM Person
    

    While I don't think this is the best solution to the question either in terms of performance or readability it is interesting as an exploration of MySQL's string functions. Keep in mind that FIELD's output does not seem to be case sensitive. I.e., FIELD('A','A') and FIELD('a','A') both return 1.

提交回复
热议问题