数据库的增删改查
–创建表
create table t_user (
id int primary key auto_increment,
xm varchar(20),
nl int,
xb int
)
–删除表的语法
drop table t_user
–插入操作
insert into 表名(列名...) values (值....)
insert into t_user(xm,nl,xb) values ('大傻子1',12,0);
insert into t_user(xm,nl,xb) values ('大傻子2',13,0);
insert into t_user(xm,nl,xb) values ('大傻子3',14,0);
insert into t_user(xm,nl,xb) values ('大傻子4',15,1);
insert into t_user(xm,nl) values ('大傻子5',15);
–删除操作
delete from 表名 [where 筛选条件]
--条件筛选的运算符号 = <> > < >= <= like not like in not in is null is not null between and not between and and or
delete from t_user where xm like '大%'
delete from t_user where xm not like '大%'
delete from t_user where xm in ('大傻子1','大傻子2')
delete from t_user where xm not in ('大傻子1','大傻子2')
delete from t_user where xb is null
delete from t_user where xb is not null
delete from t_user where nl between 12 and 14
delete from t_user where nl not between 12 and 14
delete from t_user where xm like '大%' and xb=0
delete from t_user where xb =1 or xb is null
–更新表的语法
update 表名 set 列名=新值,列名=新值,列名=新值...[where 删选条件]
update t_user set xm='小傻子',nl=100 where xb is null
–查询语法
select 字段名... from 表名 [where 条件]
[分组][分组过滤][排序]
select * from t_user where xm like '大%' and xb=0
–聚合函数 count avg sum max min
select count(*),xb from t_user group by xb
select sum(nl),xb from t_user group by xb
select count(*),xb from t_user where nl>13 group by xb having xb=0
select * from t_user order by nl
select * from t_user order by nl desc
–创建表
create table tm_class(
id int primary key auto_increment,
bjmc varchar(20),
bjrl int,
bjms text
)
create table tm_student(
id int primary key auto_increment,
xm varchar(20),
nl int,
xb int,
cid int
)
–添加外键
alter table tm_student add constraint tm_studentfk01 foreign key (cid) references tm_class(id)
insert into tm_student(xm,nl,xb,cid) values('小白2',22,1,2)
insert into tm_class(bjmc,bjrl,bjms) values ('ts1708',30,'CSS')
select * from tm_class
drop table tm_student
select * from tm_student
delete from tm_student where cid=100
insert into tm_student (xm,nl,xb,bjmc,bjrl,bjms) values ('小红2',14,0,'ts1706',40,'讲JAVA的');
insert into tm_student (xm,nl,xb,bjmc,bjrl,bjms) values ('小红3',15,1,'ts1706',40,'讲JAVA的');
insert into tm_student (xm,nl,xb,bjmc,bjrl,bjms) values ('小红4',16,0,'ts1706',40,'讲JAVA的');
insert into tm_student (xm,nl,xb,bjmc,bjrl,bjms) values ('小红5',17,1,'ts1706',40,'讲JAVA的');
–内连接
select tm_student.* from tm_class
inner join tm_student
on tm_class.id = tm_student.cid
where tm_class.bjmc='ts1706'
select count(*),tm_class.bjmc from tm_class
inner join tm_student
on tm_class.id = tm_student.cid
group by tm_class.bjmc
select * from tm_class
inner join tm_student
on tm_class.id = tm_student.cid
–外连接
select tm_class.bjmc from tm_class
left join tm_student
on tm_class.id = tm_student.cid
where tm_student.id is null
select * from tm_student
right join tm_class
on tm_class.id = tm_student.cid
select * from t_user