一、SQL
1、结构化查询语言,用于关系型数据库
2、不区分大小写
二、SQL语句——表操作
1、创建表
create table 表名(
字段名 类型 约束,
)
create table students(
id int unsigned primary key auto_increment, #主键,自动递增
name varchar(10) ,
age int unsigned,
height decimal(5,2) #身高是小数,总长度是5位,小数点后是2位
)
2、删除表
(1)drop table 表名 #如果表存在则删除,如果表不存在则会报错
(2)drop table if exists 表名
三、SQL语句——数据操作
1、添加数据
insert into 表名 values(...)
(1)给所有的字段插入数据
insert into students values(0,'张三',20,1.75) #第一位主键位置,通常写0或者default或者null来占位
(2)给指定字段插入数据
insert into students(name) values('李四')
2、修改数据
update 表名 set 字段=值 where 条件
update students set name='狄仁杰',age=18 where id=1
3、删除数据
delete from 表名 where 条件
delete from students where id=1
4、查询数据
(1)select * from 表名
(2)select 字段1,字段2,字段3 from 表名 where 约束
(3)起别名 as
select name as 姓名,sex as 性别 from students #给字段起别名
select name,sex from students s #给表起别名
(4)去重 distinct
select distinct sex from students
(5)比较运算符
>,<,!=
(6)逻辑运算符
or,and,not
select * from students where not hometown='北京'
(7)模糊查询 like
%表示任意多个字符
_表示任意一个字符
select * from students where name like '孙%'
(8)范围查询 in,between and
select * from students where hometown in('北京','上海','广州')
select * from students where age between 18 and 25
select * from students where not age between 18 and 25 #年龄不在18到25之间
(9)空判断
判空 is null
判断非空 is not null
5、排序 order by
asc 升序
desc 降序
select * from students order by age asc #按照年龄升序排列
select * from students order by age desc,studentno desc #先按照年龄从大到小排序,年龄相同时再按照学号降序排列
6、聚合函数
count(*) 计数
max 求最大值
min 求最小值
sum 求和
avg 求平均值
select max(age) from students where sex='女' #查询女生中的最大年龄
7、分组 group by
(1)select sex,count(*) from students group by sex #查询各种性别的人数
(2)分组过滤 having
select sex,count(*) from students group by sex having sex='男' #查询男生总人数