创建表用括号
create table c( id int , name varchar(20), age tinyint unsigned );
插入多行:insert into 表名( ) values( ) ,()
varchar 字符串 单引号双引号都可以
在插入单行时,使用values比value快
在插入多行时,使用value比values快
1、bigint:从-263(-9223372036854775808)到263-1(9223372036854775807) 的整型数据(所有数字),存储大小为8个字节。
2、int:从-231(-2147483648)到231-1(2147483647)的整型数据(所有数字)。存储为4个字节。
3、smallint:从-215(-32768)到215-1(32767)的整型数据。存储大小为2个字节。
4、tinyint:从0到255的整型数据。存储大小为1个字节。
update 表 set 字段=值 where
update c set age=age+1 where id>10
delete from 表名 where
truncate table 表名 –删除表中所有数据
如果想保留表将所有数据删除,自增长字段恢复从1开始用truncate
drop table (if exists)表名
字段的约束
primary key 主键 不能重复
auto increment自增(如果指定了id会变成指定的,后面的从指定的这个值开始自增)
如果不指定字段,主键自增长字段的值可以用占位符0或者null
not null非空
unique 唯一
default 默认值(当没有指定当前字段的值时才会使用 )
distinct 消除重复记录
select distinct 字段名,字段名 from 表名
逻辑运算符
and
or
not
where sex!=‘nv’ 等于where not sex =nv
模糊查询
like ’ 孙%‘ 以孙开头
__ 只有一个字
范围查询
in(a,b,c) 3个里面的一个
between A and B 包含a和b
空判断
is (not)null
=后面只能写明确的值
排序
order by 字段名 asc(可省略) /desc(从大到小)
如果有多个字段加上,
年龄相同时,按学号从小到大排 select * from students order by age desc , studentNo
先where再order by
条件必须要在排序之前
select 语句特有的
聚合函数
select count(sex) from student会出现总的个数重复的也会算 select count(distinct sex) from student 只会出现不重复的一个有多少次
聚合函数不能用到where里面
avg里面不计算null
分组聚合之后的数据筛选
having要在group by之后
having在分组聚合之后筛选,但是不能在having里面找和聚合函比较的东西
求班级人数大于3人的班级
select class,count()* from students group by class having count(*)>3
having里面可以用聚合函数
查询班级总人数大于2人的班级名称和班级对应的总人数
select class,count(*) from students group by class having count(*)>2
查询平均年龄大于30岁的班级名称和班级总数
select class,count(*) from students group by class having avg(age)>30
limit数据分页显示
查询前3行
select * from students limit (0),3
从第一条数据开始的3条记录,那个0可以不写
select * from 表名 where 条件 group by 字段 order by 字段 limit start ,count
查询年龄最大同学的name
select name from students group by age desc limit 0,1
查询年龄最小的女同学的信息
select * from students group by gender having age=min(age)错
select * from students where sex='女' order by age limit 1
内连接
inner join只显示相同的部分
select students.name, s.courseNo, s.score from students inner join scores s on students.studentNo = s.studentNo where students.name = '王昭君'
多表内连接
带有order by的多连接
select name,c.courseNo,score from students s1 inner join scores s2 on s1.studentNo = s2.studentNo inner join courses c on s2.courseNo = c.courseNo where sex='男' order by score desc limit 1
左右连接
自连接
select a2.name from areas a1 inner join areas a2 on a1.id = a2.pid where a1.name = '广东省' and a1.id = a2.pid
子查询
表级子查询
一个utf8汉字占3个字符
视图不能删除里面的数据,只是一个虚表
begin
rollback
索引
主键:不能重复
everything用来查找电脑上的软件