表的约束
在统计数值时会出现问题
不能为空因为
数+NULL=NULL
加not null default _数值_
set和enum不能设置默认值。
列描述:comment,没有实际含义,专门用来描述字段,会根据表创建语句保存,用来给程序员或DBA来进行了解。
# desc无法查看注释信息 但是可以通过show查看 show create table name;
zerofill
对数值前填充 0//一种格式化输出 设置zerofill该列自动
主键
primary key //该列不能为空,不能重复,一张表只能有一个主键 复合主键: primary key (id,name) 当表创建好以后可以追加主键 alter table 表名 add primary key(字段列表)//一旦有不满足主键的约束条件数据,操作失败
删除主键
alter table t3 drop primary key
自增键
必须是键 id int unsigned primary key auto_increment
唯一键
允许为空 id char(10) unique
表的增删改查 (CRUD)
- 增加 insert into (讲了)
字符、日期应该有单引号 ‘Jan’、’一头牛’
一次增加(插入)多条记录用’,’隔开
insert into test values ('cat','kitty'),('dog','dahuang');
更新(like)
replace into goods values (1,'fish',9);//比这条简单: insert into 表名(字段列表) values(值列表) on duplicate key update 字段=新值;
表的更新(like)
update goods set price=100; update goods set price=40 where id=1;
去掉表中某个值可以update成‘ ’空格
select count(*) from goods2//统计条数
删除
#
delete from name where ...
truncate from name;
delete 与 truncate 的区别
*效果一样,truncate更快
*delete可以带where条件,删除更加灵活
*delete可以返回删除的记录数,而truncate返回0
*推荐使用delete
delete
*如果不适用where子句,将删除整个表中所有数值
*delete语句不能删除某一列的值(可以用update置null)
*推荐使用delete
表格复制
#
create table table_name1 like table_name2;
数据克隆
insert into tanle_name2 select * from table_name1;
select (查)
select distinct math from student; //distinct查询并去掉重复 select name,chinese+math +english (as) total from student //查询起别名,as可以缺省 select name,(chinese+math+english)*1.6 as total from student where name like '红%';//姓红的总分加60% '红%' 查第二个时,第一个用_代替 '_孩%' //单字符代替符_,红孩儿 //永远不要把%放在最前面,效率很低。 select * from student where math in(89,91,90);//数学成绩是这么多的人用in
order by 在后执行//默认升序
# select chinese+english +math as total from student order by total;//asc默认升序 select chinese+english +math as total from student order by total desc; //降序 where 先执行
where后面不能直接跟max()之类的集函数
查询
分页显示limit 3,2;
select chinese+english +math as total from student order by total desc limit 0,3;//显示前三行(搜索内容分页显示就是这么做)
count
count不统计null
- min/max
select name,min (math) from student //最小值
select name,math from student where math=min(math); //思路,语句是错的
select name,math from student where math=(select min(math) from student);//正确
sum (只对数值起作用)
select name,sum(math)/count (math) from student //求数学平均数,sum只能统计数值。 select avg(math)from student//求平均数 select format (avg(math +english+chinese ),2)from student // format(结果,小数点位数)