数据库 查询 sql语句(高级1)

查询

—查询制定字段

select 字段1,字段2 from 表名;

—给字段起别名

select 字段 as 别名 from 表名;

—给表起别名

select 别名.字段,别名.字段 from 表名 as 别名;

—消除重复行

select distinct 字段 from 表名;

条件查询

"""以下例子:表名 student 字段有:name,age,gender,height"""

—比较运算符:select ……from where …….

">" "<" "<="  ">=" "="  "!=" "<>"

—- “>”

select * from students where age >18;

—-逻辑运算符

"and"  "or" "not"

–and

18 和28 之间的所有学生信息
select * from students where age >18 and age<28;
18以上的女性
select * from students where age >18 and gender="女"

–or

18以上或者身高    高过180(包含)以上
select * from students where age >18 or height >= 180;

–not

不在18岁以上的女性这个范围内的信息
select * from students where not(age >18 and gender ="女")

模糊查询

like
% 替换任意一个
_ 替换一个

---查询姓名中以"小"开始的名字
select * from students where name like "小%";
 ---查询姓名中有小的所有名字
 select * from students where name like "%小%";
 ---查询有3个字的名字
 select * from students where name like "___" (引号里面是三个下划线)
 ---查询至少有2个字的名字
 select * from students where name like "__%";

—范围查询

in(1,4,8)表示在一个非连续的范围内

 --查询 年龄为18 或34 的姓名
 简单版:select name from students where age = 18 and age = 34;
 改进版:select name from students where age in(18,34);

—not in 不非连续的范围之内

--年龄不是18 或34 的信息
select * from students where not in (18,34);

—between ….. and ….. 表示在一个连续的范围内

查询年龄在18 到34 之间 信息
select * from students where age between 18 and 34;

—not between….and….表示不在一个连续的范围内查询

查询年龄不在18 到34 之间的信息
select *from students where age not between 18 and 34;

—空判断
–判空 is null
–判非空is not null

查询身高为空的信息
select * from students where height is null;
查询身高不为空的信息
select * from students where height is not null;

排序

—order by 字段
—asc 从小到大排序 即升序
—desc 从大到小排序 即降序

查询年龄在18到34岁之间的男性,按照年龄从小到大的顺序排序
select * from students where (age between 18 and 34) and gender ="男" order by asc;

聚合函数

—总数 count

查询男性有多少人
select count(*) from students where gender="男";

—最大值(max)

查询最大的年龄
select max(age) from students;
查询女性的最高身高
select  max(height) from students where gender ="女";

—最小值(min)

查询最小的年龄
select min(age) from students;

—求和(sum)

计算所有人的年龄总和
select sum(age) from students;

—平均值(avg)

计算平均年龄
select avg(age) from students;

—四舍五入 round(123.22,2) 保留两位小数

计算多有人的平均年龄,保留2位小数
select round(avg(age),2) from students;
计算男性的平均身高,保留2位小数
select round(avg(height),2) from students where gender="男"; 

Star_Wang_ 2018.5.14

发布了4 篇原创文章 · 获赞 13 · 访问量 390

猜你喜欢

转载自blog.csdn.net/qq_41957173/article/details/80314359