Home > Database > Mysql Tutorial > What are the benefits of using mysql's case method?

What are the benefits of using mysql's case method?

coldplay.xixi
Release: 2020-10-19 16:13:43
Original
3596 people have browsed it

The benefits of using the case method of mysql: 1. Flexible organization format when displaying query results; 2. Effectively avoiding multiple accesses to the same table or several tables.

What are the benefits of using mysql's case method?

Benefits of using mysql's case method:

select has two biggest benefits when used in conjunction with case. First, the format can be flexibly organized when displaying query results, and second, multiple accesses to the same table or several tables are effectively avoided.

The following is a simple example to illustrate. For example, the table students(id, name, birthday, sex, grade) requires statistics on the number of boys and girls according to each grade.

The header of the statistical results is, grade, number of boys, number of girls . If you don't use select case when, in order to display the number of men and women side by side, it will be very troublesome to count. You must first determine the grade information, and then take the number of boys and girls according to the grade, and it is easy to make mistakes.

Use select case when to write as follows:

SELECT grade, COUNT (CASE WHEN sex = 1 THEN 1     
                            ELSE NULL
                        END) 男生数,
               COUNT (CASE WHEN sex = 2 THEN 1
                            ELSE NULL
                       END) 女生数
FROM students
GROUP BY grade;
Copy after login

More related free learning recommendations: mysql tutorial (video)

The above is the detailed content of What are the benefits of using mysql's case method?. 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