SQL语句快速复习笔记
create table student(
_id INT NOT NULL,
_name varchar(20),
_teacher int,
primary key(_id),
index index_1(_name)
);
create table teacher(
_id INT NOT NULL,
_name varchar(20),
primary key(_id)
);
alter table student add constraint FK_ID foreign key(_teacher)
REFERENCES teacher(_id);
insert into student(_id,_name,_teacher)values(1,"学生1",1);
insert into student(_id,_name,_teacher)values(2,"学生2",1);
show tables;
drop table student;
describe tb1;
insert into teacher(_id,_name)
values(1,"老师_1");
select s._id,s._name,t._name from student s join teacher t on t._id=s._id;
select *from student s,teacher t where s._teacher = t._id;
update student set _name = "学生_1" where _id = 1;
select *from student;
delete from student where _id = 1;
select *from student where _name like '学%';
select _id,_name from student
union
select _id,_name from teacher;
select _id,_name from student
union
select _id,_name from teacher
order by _id desc;
select coalesce(author,'总数') as author,count(title_2) as book_count from tb1 where author is not null
group by author WITH ROLLUP;
select coalesce(author,'总数'),count(title_2) as book_count from tb1 where author is not null
group by author WITH ROLLUP
having count(book_count)>2;
select * from tb1 where author regexp '^小';
begin;
insert into student(_id,_name,_teacher)values(3,"学生3",1);
insert into student(_id,_name,_teacher)values(4,"学生4",1);
commit;
select *from student;
begin;
insert into student(_id,_name,_teacher)values(5,"学生5",1);
select *from student;
rollback;
alter table tb1 add test int after id;
desc tb1;
alter table tb1 drop test;
desc tb1;
alter table tb1 modify id int not null auto_increment;
desc tb1;
alter table tb1 change title title_2 varchar(100);
desc tb1;
show table status;
alter table tb2 rename to tb1;
show tables;
alter table student drop foreign key FK_ID;
create index index_1 on tb1(id);
show index from tb1;
drop index index_1 on tb1;
show index from tb1;
create unique index unique_index on tb1(title_2);
show index from tb1;
create fulltext index fullIndex on tb1(author);
drop index fullIndex on tb1;
drop procedure if exists InsertDataInTb1;
delimiter
create procedure InsertDataInTb1()
begin
declare i int default 0;
declare title varchar(20) default 'title_' ;
while i<100 do
insert into tb1
(title_2,author,sdate)
values
(concat('title',i),concat('author_',i),curdate());
set i = i+1;
end while;
end
DELIMITER ;
call InsertDataInTb1();
create temporary table temporary_table(
id int primary key not null,
temp_name varchar(99)
);
show create table tb1;
create table tb2 like tb1;
insert into tb2 select *from tb1;
select *from tb2;
create table tb3 select *from tb1;
desc tb3;
select *from tb2;
select LAST_INSERT_ID();