SQL语句--sql增删改查语句
程序员文章站
2022-07-10 12:14:34
...
#增删数据库
create database if not exists learn; #创建数据库learn
drop database db; #消除数据库db
#完整性约束条件(6个)
primary key: 主键 (唯一不为空,一个表只有一个主键)
auto_increment : 自增长(必须为主键字段)
FOREIGN KEY : 外键
not null : 非空
unique: 唯一 (可以为空,且一个表可以有多个)
default : 默认值
#创建表tname1
create table tablename1 (
t1_id int primary key auto_increment,
name varchar(20) not null,
address varchar(40),
birthday date,
sex bit(1),
phone char(11)
)ENGINE= MYISAM character set utf8mb4;
create table tablename2 (
t2_id int primary key auto_increment,
name varchar(20) character set utf8mb4,
address varchar(40),
birthday date,
sex bit(1),
phone char(11)
)ENGINE= MYISAM character set utf8mb4; #将这张表的字符串编码设置为utf8mb4,不然输入中文的时候会乱码
#修改表结构
#查看表结构
desc tablename1;
#添加字段
alter table tablename1 add vocation varchar(40) character set utf8mb4 AFTER phone;
alter table tablename2 add vocation varchar(40) character set utf8mb4;
alter table tablename1 add t_id int first;
#修改字段
alter table tablename1 change t_id t_id0 int;
alter table tablename2 change name name varchar(20) character set utf8mb4 not null;
alter table tablename1 modify t_id0 varchar(11);
alter table tablename1 modify t_id0 varchar(11) after vocation;
#删除字段
alter table tablename1 drop t_id0;
#重命名
alter table tablename1 rename to tname1;
rename table tname1 to tablename1;
#查看表结构
desc tablename1;
#查看全部数据
select * from tablename1;
#插入数据
#向全部字段添加数据
insert into tablename1 values (1,"Jalen","上海市",19911208,1,"18528191312","IT");
#向部分字段添加数据
insert into tablename1 (name,address,birthday,sex,vocation) values ("XR","广州市",19920725,0,"IT");
#批量数据插入到tablename2
insert into tablename2 (name,address,birthday,sex,vocation)
values("XA","广州市",19920321,0,"IT"),("XB","广州市",19940826,1,"IT");
#修改表中数据
update tablename2 set address = "北京市" , sex = 1 where name = "XA";
#复制表结构和数据
#同时复制表结构和数据到新表(新表会去除约束条件),做2次表查询使用时常用
create table tablename3
select name,address,birthday,sex,phone,vocation from tablename2
where t2_id between 1 and 2;
#只复制表结构到新表(会去除主键和自增约束)
create table tablename4 select * from tablename2 where 1=2;
#或者(只复制表结构到新表,所有约束条件均不改变)
create table tablename5 like tablename2;
#只复制表数据到已存在的其他表对应字段中
insert into tablename4 (name,address,birthday,sex,phone,vocation)
select name,address,birthday,sex,phone,vocation from tablename2
where t2_id between 1 and 2;
#删除(删除表,删除表字段,条件删除表数据,清空表)
#删除整个表
drop table tablename5;
#删除表字段
alter table tablename4 drop name;
#条件删除表数据(当没有where限制条件时,等价于清空表,但是自增限制条件依然继续,逐行删除)
delete from tablename4 where address = "北京市";
#清空表(自增条件也清空重置,全部数据一起删除,效率更高)
truncate table tablename4;