mysql-条件查询

一、准备工作:

-- 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期');

二、查询例子

(1)去重查询

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

(2)where条件查询

1、比较运算符查询(太简单了就不演示)

2、逻辑运算符查询(太简单了就不演示)

3、模糊查询

 

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

4、范围查询

select * from students where age between 18 and 50;

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

5、查找空值

select * from students where height is null;

6、排序查询

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

7、聚合函数

(1)count()查询有多少男性

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

(2)查询身高最高的人信息

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

(3)查询年龄总和

select sum(age) from students;

(4)查询平均年龄

select avg(age) from students;

(5)计算平均年龄去小数点后两位

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

猜你喜欢

转载自blog.csdn.net/qq_39197555/article/details/113870294