Home  >  Article  >  Daily Programming  >  How to implement decode in mysql

How to implement decode in mysql

下次还敢
下次还敢Original
2024-04-27 05:54:15961browse

The decode function in MySQL can convert the input value into a specified value based on specified conditions. Syntax: DECODE(expr, value1, result1, value2, result2, ..., valueN, resultN, default). The function checks from left to right whether the condition value matches the input value. If it matches, it returns the corresponding result. If it does not match, it returns the default value.

How to implement decode in mysql

Implementation of decode in MySQL

decode function

The decode function is used in MySQL to convert an input value into a specified value, based on whether the input value meets specified conditions. The syntax is as follows:

<code>DECODE(expr, value1, result1, value2, result2, ..., valueN, resultN, default)</code>

Parameter description:

  • expr: The expression to be evaluated.
  • value1, value2, ..., valueN: The condition value to be checked.
  • result1, result2, ..., resultN: Return result when matching the corresponding condition value.
  • default: The default result when the input value does not match any condition value.

Working principle:

The decode function checks whether the condition value matches the expr value one by one from left to right. If there is a match, the result associated with the condition value is returned. If no match is found, the default value is returned.

Example:

<code>SELECT DECODE(gender, 'M', 'Male', 'F', 'Female', 'Unknown');</code>

This example converts the value of the gender field to human-readable text:

  • If the gender value is ' M', then return 'Male'.
  • If the gender value is 'F', return 'Female'.
  • If the gender value is not 'M' or 'F', 'Unknown' is returned.

Note:

  • decode function is case-sensitive.
  • The default value is optional. If not provided, the function returns NULL when expr does not match any condition value.
  • The decode function can handle multiple conditions, and up to 127 condition values ​​and results can be specified at the same time.

The above is the detailed content of How to implement decode in mysql. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn