一、DDL操作数据库
1.显示数据库:show database;
2.创建数据库:create database name;
3.创建数据库名称不能重复以判断的方式来创建:create database if not exists db1;
4.删除数据库:drop database db1;
5.删除时判断:drop database if exists db1;
6.使用数据库:use db1;
7.查看当前使用的数据库:select database();
二、DDL操作表
- 查询表:show tables;
- 查看表结构:desc func;
- 创建表:create table 表名(字段名 数据类型1,字段名1 数据类型2...);
create table tb_user(
id int,username varchar(20),password varchar(32)
);
- sql数据类型:数值,日期,字符串等
char 定长字符串 存储性能高一点,相对于varchar;浪费空间;空间换时间
varchar 变长字符串
- 创建学生表练习:
create table student(
id int,
name varchar(10),
gender char(1),
brithday date,
score double(5,2),
email varchar(64),
tel varchar(15),
status tinyint
);
- 删除表:drop table 表名;(直接删除)
- 判断后删除:drop table if exists tb_user;
- 修改表名:alter table 表名 rename to 新表名;
alter table staudent rename to stu;
- 添加一列: alter table 表名 add 列名 数据类型;
alter table stu add address varchar(50);
desc stu;
- 修改数据类型:alter table 表名 modify 列名 新数据类型;
alter table stu modify address char(50);
- 修改列名和数据类型:alter table 表名 change 列名 新列名 新数据类型;
alter table stu change address addr varchar(30);
desc stu;
- 删除列:alter table 表名 drop 列名;
alter table drop addr;
三、DML(对表中数据进行增删改)
- 给指定列添加数据 insert into 表名(列名1,列名2,...) values(值1,值2);
insert into stu(id,name) values(1,"张三");
- 给全部列添加数据 insert into 表名 values(值1,值2,...);
- 批量添加数据
insert into 表名(列名1,列名2)values(值1,值2..),(值1,值2..)...;
insert into stu(id, name, sex,birthday,score,email,tel,status) values(2,'李四','男','1999-11-11',88.88,'lishi@qq.com','13812345678',1);
insert into stu values(2,'李四','男','1999-11-11',88.88,'lishi@qq.com','13812345678',1);
- 给所有列添加数据,它的列名列表可以省,但不建议省略。
- 修改数据:update 表名 set 列名1=值1,列名2=值2,...[where 条件];
update stu set sex = '女' where name = '张三';
update stu set birthday = '1999-12-12',score = 99.99 where name='张三';
如果update语句没有跟where ,就会将表中所有数据全部修改
-
删除数据:delete from 表名 [where 条件]
删除张三记录
delete from stu where name = '张三';
如果不加where条件就会删除表呢所有数据
四、DQL数据查询操作
select 字段列表
from 表名列表
where 条件列表
group by 分组字段
having 分组后条件
order by 排序字段
limit 分页限定
- 查询多个字段
select 字段列表 from 表名;
select * from 表名;查询所有数据
- 去除重复记录
select distinct 字段列表 from 表名;
- 起别名:as ;as可省略
- 查询name age两列
select name,age from stu;
select * from table;
- 查询地址信息
select address from stu;
select distinct address from stu;
- 查询姓名,数学成绩,英语成绩
select name,math,enlish from stu;
select name,math as '数学成绩',enlish ’英语成绩';
- 查询年龄大于20岁的学员信息
select * from stu where age > 20;
- 查询年龄大于等于20的学员信息
select * from stu where age > =20;
- 查询年龄大于等于20且小于等于30的学员信息
select * from stu where age >= 20 and age <= 30;
select * from stu where age between 20 and 30;
- 查询入学日期在’1998-09-01‘到’1999-09-01‘之间的学员信息
select * from stu where hire_date bewteen '1998-09-01' and '1999-09-01';
- 查询年龄等于18岁的学员信息
select * from stu where age = 18;
- 查询年龄不等于18的学员信息;
select * from stu where age != 18;
select * from stu where age <> 18;
- 查询年龄等于18或年龄等于20或年龄等于22岁的学员信息
select * from where age =18 or age = 20 or age = 22;
select * from stu where age in (18,20,22);
- 查询英语成绩为null的学员信息(null值得比较不能用= 和!=
select * from stu where english