mysql-conditional query

1. Preparation:

-- students表
create table students(
    id int unsigned primary key auto_increment not null,
    name varchar(20) default '',
    age tinyint unsigned default 0,
    height decimal(5,2),
    gender enum('男','女','中性','保密') default '保密',
    cls_id int unsigned default 0,
    is_delete bit default 0
);

-- classes表
create table classes (
    id int unsigned auto_increment primary key not null,
    name varchar(30) not null
);


-- 向students表中插入数据
insert into students values
(0,'小明',18,180.00,2,1,0),
(0,'小月月',18,180.00,2,2,1),
(0,'彭于晏',29,185.00,1,1,0),
(0,'刘德华',59,175.00,1,2,1),
(0,'黄蓉',38,160.00,2,1,0),
(0,'凤姐',28,150.00,4,2,1),
(0,'王祖贤',18,172.00,2,1,1),
(0,'周杰伦',36,NULL,1,1,0),
(0,'程坤',27,181.00,1,2,0),
(0,'刘亦菲',25,166.00,2,2,0),
(0,'金星',33,162.00,3,3,1),
(0,'静香',12,180.00,2,4,0),
(0,'郭靖',12,170.00,1,4,0),
(0,'周杰',34,176.00,2,5,0),
(0,'凌小小',28,180.00,2,1,0),
(0,'司马二狗',28,120.00,1,1,0);

-- 向classes表中插入数据
insert into classes values (0, "python_01期"), (0, "python_02期"),(8,'Python_03期');

Two, query examples

(1) De-duplicate query

--使用distinct关键字对被查询的内容修饰
select distinct  gender from  students;    

(2) Where condition query

1. Comparison operator query (not to demonstrate if it is too simple)

2. Query of logical operators (do not demonstrate if it is too simple)

3. Fuzzy query

 

select * from students where name like "%小%";

4. Range query

select * from students where age between 18 and 50;

select * from students where age in (18,28);

5. Find null values

 

select * from students where height is null;

6. Sort query

select * from students order by age asc , height asc;

7. Aggregate functions

(1) count() queries how many men there are

select count(gender) from students where gender=1;

(2) Query information about the tallest person

select * from students where age=(select max(age) from students);

(3) Query the total age

select sum(age) from students;

(4) Query the average age

select avg(age) from students;

(5) Calculate the average age to two decimal places

 select round(avg(age), 2) from students;

Guess you like

Origin blog.csdn.net/qq_39197555/article/details/113870294