type
status
date
slug
summary
tags
category
icon
password
URL
Sep 1, 2022 09:23 AM
操作数据库:CRUD(Create Retrieve Update Delete)
create database dbname;
create database if not exists db1;
create database db2 character set gbk;
create database if not exists db3 character set gbk;
show databases;
show create database dbname;
alter database db2 character set uft8;
drop database db2;
drop database if exists db2;
使用数据库
select database();
use db1;
操作表
C 创建
create table tablename(
id int,
name varchar(32),
age int,
score double(4,1),
birthday date,
insert_time timestamp
);
复制:create table stu like student;
注意:最后一列不需要加逗号
数据库类型:
- int:整数类型,如age
- double:小数类型,如score
- date:日期,只包含年月日,yyyy-MM-dd
- datetime:日期,包含年月日时分秒,yyyy-MM-dd HH:mm:ss
- timestamp:时间戳类型,包含年月日时分秒,yyyy-MM-dd HH:mm:ss
- varchar:字符串,如name varchar(20):姓名最大二十个字符
R 查询
show tables;
desc tablename;
U 修改
- 修改表名
- alter table tablename rename to newtablename;
- 修改表的字符集
- alter table tablename character set utf8;
- 添加一列
- alter table tablename add column int;
- 修改列名称 类型
- alter table tablename change columnname newcolumanname newdatatype;
- alter table tablename modify columnname newdatatype;
- 删除列
- alter table tablename drop columnname;
D 删除
drop table tablename;
drop table if exists tablename;
客户端图形化工具:SQLYog,DBeaver,WorkBench
DML:增删改表中数据
添加数据
语法:
insert into 表名(列名1,列名2,列名3) values(值1,值2,值3);
注意:
- 列名和值要一一对应
- 如果表名后,不定义列名,则默认给所有列添加值
- 除了数字类型,其她类型需要使用引号(单双引都可以)
删除数据
语法:
delete from 表名 where 条件;
delete from 表名;(不推荐,效率低)
truncate table 表名;(删除表,再重新创建一张一样的空表)
workbench删除需要更新safe update为0
SET SQL_SAFE_UPDATES = 0;
修改数据
语法:
update student set age=22 where id =1;
如果不加任何条件,则会将表中的所有记录全部修改;
DQL:查询表中的记录
- select * from 表名;
- 语法:
- select 字段列表
- from 表名列表
- where 条件列表
- group by 分组字段
- having 分组之后的条件
- order by 排序
- limit 分页限定
基础查询
- 多个字段的查询
- select 字段1,字段2,字段3,from 表名;
- 去除重复
- distinct
- 计算列
- 一般可以使用四则运算计算一些列的值。(一般只会进行数值型的计算)
- ifnull(表达式1,表达式2)
- 表达式1:那个字段需要判断是否为null
- 如果该字段为null后的替换值
- 起别名
- as: as也可以省略
条件查询
- < > <=
- between and
- in
- like
- _:单个任意字符
- %:多个任意字符
- is null
- and
- or
- not
例子:
select * from student where age>=20;
select * from student where age>=20 and age <=30;
select * from student where age between 20 and 30;
select * from student where age =22 or age =19 or age = 25;
select * from student where age in (22,18,25);
select * from student where english is null;
select * from student where english is not null;
select * from student where name like "zhao%";
select * from student where name like "____li%";
select * from student where name like "____";
select * from student where name like "%zhao%";