Use of case in MySQL

Source: Internet
Author: User

Syntax Description:
Way One:
Case value when [compare_value] and then result [when [compare_value] then result ...] [ELSE result] END
Way two:

case is [condition] then result [when [condition] then result ...] [ELSE result] END


Examples of Use:

Mysql> Select Id,name, (gender) as ' sex ' from t_user;
+----+------------+------+
| ID | name | sex |
+----+------------+------+
| 19 | Zhang San | 1 |
| 20 | Little Red | 2 |
| 21 |      Super Admin | |
+----+------------+------+
3 Rows in Set (0.00 sec)


Mysql> Select Id,name, (case gender if 1 then ' Male ' when 2 then ' women ' else ' other ' END) as ' sex ' from t_user;
+----+------------+------+
| ID | name | sex |
+----+------------+------+
| 19 | Zhang San | Male |
| 20 | Little Red | Women |
| 21 | Super Admin | Other |
+----+------------+------+
3 Rows in Set (0.00 sec)


Mysql> Select Id,name, (case is gender=1 then ' Male ' when gender=2 then ' women ' else ' other ' END) as ' gender ' from T_user;
+----+------------+------+
| ID | name | sex |
+----+------------+------+
| 19 | Zhang San | Male |
| 20 | Little Red | Women |
| 21 | Super Admin | Other |
+----+------------+------+
3 Rows in Set (0.00 sec)


Application of Common view:

Eg: In the Forum, the type of different types of posts are not the same, sticky stickers are always on the top, and the essence of paste and ordinary paste in the sort is the same, at this time can use the MySQL case, so that in the sorting of the essence and the type of the ordinary paste is the same.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.