Home > Database > Mysql Tutorial > How to use mysql case when?

How to use mysql case when?

coldplay.xixi
Release: 2020-06-24 08:58:16
Original
33789 people have browsed it

How to use mysql case when?

mysql case when usage:

MySQL has two syntaxes for case when:

Simple function

CASE [col_name] WHEN [value1] THEN [result1]…ELSE [default] END
Copy after login

Search function

CASE WHEN [expr] THEN [result1]…ELSE [default] END
Copy after login

What is the difference between these two syntaxes?

1. Simple function

CASE [col_name] WHEN [value1] THEN [result1]…ELSE [default] END: Enumerate this All possible values ​​of the field.

SELECT
    NAME '英雄',
    CASE NAME
        WHEN '德莱文' THEN
            '斧子'
        WHEN '德玛西亚-盖伦' THEN
            '大宝剑'
        WHEN '暗夜猎手-VN' THEN
            '弩'
        ELSE
            '无'
    END '装备'
FROM
    user_info;
    SELECT
Copy after login
    NAME '英雄',
    CASE NAME
        WHEN '德莱文' THEN
            '斧子'
        WHEN '德玛西亚-盖伦' THEN
            '大宝剑'
        WHEN '暗夜猎手-VN' THEN
            '弩'
        ELSE
            '无'
    END '装备'
FROM
    user_info;
Copy after login

2. Search function

CASE WHEN [expr] THEN [result1]…ELSE [default] END: The search function can write judgments , and the search function will only return the first qualified value, and other cases will be ignored

# when 表达式中可以使用 and 连接条件
SELECT
    NAME '英雄',
    age '年龄',
    CASE
        WHEN age < 18 THEN
            &#39;少年&#39;
        WHEN age < 30 THEN
            &#39;青年&#39;
        WHEN age >= 30
        AND age < 50 THEN
            &#39;中年&#39;
        ELSE
            &#39;老年&#39;
    END &#39;状态&#39;
FROM
    user_info;
Copy after login

Recommended tutorial: "mysql video tutorial"

The above is the detailed content of How to use mysql case when?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template