1.查看数据库
show databases
2.创建一个数据库
create database 数据库名称
3.删除一个数据库
drop database 数据库名称
4.进入一个数据库
use 数据库名称
5.在某个数据库中创建一个数据表
create table 表名(字段名称 字段类型,~ ~,……)
例如:create table student (
id int(6),
name varchar(10),
sex varchar(2),
age int,
schooldate date
);
/* int后不写默认为11.
double长度控制可以是两个长度,一个是总长度,一个是小数点后的长度。
记录:行; 字段:列.
字符型需加' '或" ",如'hello',"world",'你好',"世界"。
date为年——月——日,
time为时——分——秒,
datetime为年——月——日——时——分——秒。
*/
6.查询
1)查看表中所有数据
select * from 表名
2)基本查询
select 字段列表[字段1,字段2,…,字段n]from 表名
如:select name,id from stu;
其中字段可以进行基本运算
如:select salary*12 from worker;
字段前加distinct可以去重
3)条件查询
where 条件表达式(字符串需要加' ')
select * from worker where salary>100 and salary<200;
select * from worker where salary<100 or salary>200;
select * from worker where salary in(100,200,300);
in:在这个取值中,只要有一个匹配就符合条件,则被查出
not in:不在此区间范围内。
select * from worker where salary between 100 and 200;在100到200之间查询。
null 与null 做等值判断时结果永远是假,
判断一个数值是否是null需要用is null 或者is not null,
select * from worker where salary is null;
7.查看表的结构
desc 表名
8.删除一张表
drop table 表名
9.增加字段
alter table 表名 add 字段名 字段类型
例如:alter table book add count int;
10.修改字段
alter table 表名 modify 字段名 字段类型
例如:alter table book modify count int;
11.删除字段
alter alter 表名 drop 字段名称
例如:alter table book drop count;
12.向表中插入数据
insert into 表名(想插入的字段名称,~,~,……) values(想插入的字段值); //一一对应
insert into 表名 values(表中所有字段值);
13.删除数据
清空表操作:delete from 表名
delete from 表名 where 条件表达式
例如:delete from stu where num=1;
14.修改表操作
update 表名 set 字段名=新的字段值
例如:update stu set sex='male';
update stu set sex='female' where num=3;
update stu set name='tom',sex='male' where num=3;
15.约束
1)唯一约束 //表示该值只可以使用一次
create table stu(num int unique,
name varchar(11)
);
2)非空约束 //表示该值不可为空
create table stu(num int not null,
name varchar(11)
);
3)唯一非空约束
create table stu(num int unique not null,
name varchar(11)
);
4)主键自增约束 //主键与唯一非空相同,自增表示插入时该值会自动增加1
create table stu(num int primary key auto_increment,
name varchar(11)
);
/*在设置了主键自增约束后,插入语句可写为
insert into stu(name) values('张三');
或insert into stu values(NULL,''张三) 此时NULL会按照自增长策略生成*/
5)外键约束
外键必须是另一张表的主键,学生表里的班级号classnum与班级表里的num关联在一起
班级表:
create table class(num int primary key auto_increment,
name varchar(11)
);
学生表:
create table stu(num int primary key auto_increment,
name varchar(11),
classnum int,
foreign key(classnum) reference class(num)
);