学习目标:
增加数据
删除数据
更新数据
查询数据(重点)
一、回顾创建表语法
1、mysql>use 数据库名;
mysql>create table 表名 (
->列名 数据类型 [属性/约束],
......
->) [表属性];
属性/约束:
null 允许取null值
not null 不允许取null值
default 值 指定列的默认值
primary key 主键
check (条件表达式) 限制列的取值范围
UNSIGNED 作用数字型列上,限制列为无符号数
FOREIGN KEY(外键名) REFERENCES 表名 [(列名,...)] 外部键
index 索引名 定义索引
表属性:
ENGINE|TYPE= 引擎名 指定表的存储引擎的类型
实例:mysql>use db1;
mysql>create table info (
->uid varchar(5) primary key,
->uname varchar(30) not null,
->password varchar(10) null);
二、插入数据
1、insert into 表名(列名1,列名2) values(值1,值2);
2、insert into 表名 values(值1,值2);
3、批量插入:insert into 表名 values(值1,值2),(值1,值2),(值1,值2); 主键自增时必须给null
三、删除数据
1、delete from 表名 [where 条件]
2、truncate table 表名: 先删除表,再重建表;清空表中数据
四、更新数据
1、update 表名 set 列名=值, 列名=值 [where 条件]
五、查询数据(Very important)
通用格式: select [distinct] [*] [列名1,列名2] from 表名 where 条件 group by ..having 条件过滤 order by 排序
where 列名 条件;
group by 列名 having 条件:分组后过滤条件、
order by 条件 asc/desc:按条件 升序或降序;
1、关系运算符
> 、 < 、 =:大于、小于、等于
!= 、 <> : 不等于
between 1 and 10;显示1到10之间
in(1,2,3);显示在in列表中的值:1,2,3任意一个
is null、is not null;是否为空
2、逻辑运算符
and or not && || ! //于或非
3、模糊查询like
_ 表示的单个字符
% 表示的是多个字符
4、聚合函数
sum : 求和
avg() : 平均值
count() : 统计数量
max() : 最大值
min() : 最小值
5、排序order by
asc : ascend、升序
desc : descend、降序
6、分组 group by
Group by 列名;
7、as distinct ifnull
select distinct 列名 from 表名 [where 条件]; 虑重 distinct
select 列名 as 别名, 列名 as 别名,..... from 表名 [where 条件]; 别名查询 as
ifnull(列名,默认值);判断该列是否为null,如果为null,返回默认值,如果不为null,返回实际的值
总结 数据库 图