DDL:
庫
- 創建庫:create database dataname;
eg. create database 軟工1601班;- 刪除庫:drop database databasename;
eg. drop database 軟工1601班;- 查看所有庫:show databases;
表
- 創建表:create table tablename(字段名稱,字段類型,字段約束,
字段名稱,字段類型,字段約束,…)
eg. create table stu(
name varchar(10),not null COMMENT “姓名”,
id varchar(10),primary key,COMMENT “學號”,
sex enum(“man”,“woman”) COMMENT “性別”
age int COMMENT “年齡”
);- 刪除表:drop table tablename;
eg.drop table stu;- 修改表
- 修改字段類型:modify
eg.alter table stu modify name varchar(50);- 修改字段名稱:change
eg.alter table stu change id sid varchar(20);- 添加字段:add [after first]
eg.alter table stu add score float not null first;- 刪除字段:drop
eg. alter table stu drop score;- 修改表名:rename
eg.alter table stu rename student;- 查看錶
- 查看錶的創建
show create table tablename;- 查看字段
desc tablename;
字段約束
主鍵 primary key
外鍵 foreign key
唯一 unique
非空 not null
爲空 default null
字段類型
字段類型 date time datetime
DML:
插入:insert or load
- 插入數據:
insert into
tablename [(field1,field2,field3,…)]
*values(data1,data2,…);
- eg1.insert into stu values
(“002”,“張三”,“woman”,19),
(“003”,“李四”,“man”,20);- eg2.insert into
stu(id,name)
values(“004”,“王五”);
刪除:delete
刪除數據
- eg1. delete from stu;
- eg2. delete from stu where id = “001”;
修改:update
修改數據
- eg1. update stu set age = 22;
- eg2. uodate stu set age = 20 where name = “李四”;
查詢:select
- 普通查詢:
eg1. select * from stu;
eg2. select id name sex age from stu;
eg3. select name from stu where age > 20;- 去重查詢:distinct
eg. select distinct age from stu;- 排序方式:order by asc|desc 升序|降序
eg.select distinct age
from stu
order by age desc- 分組查詢:group by
select sid,SUM(score) all_score
from result
group by sid;- 多表查詢:
eg.查詢年齡小於二十歲的學生不及格信息
- 等值查詢
select name,score
from stu,result
where id = sid and age < 20 and score < 60;- 連接查詢
- 外連接查詢
- 左外連接查詢
select name,score
from
(select id,name from stu where age < 20) a
left join
(select sid,score from result where score < 60) b
on id= sid
where score is not null;- 右外連接查詢
select name,score
from
(select id,name from stu where age < 20) a
right join
(select sid,score from result where score < 60) b
on id= sid
where name is not null;- 全外連接查詢
select name,score
from
(select id,name from stu where age < 20) a
full join
(select sid,score from result where score < 60) b
on id= sid
where name is not null;- 內連接查詢
select name,score
from
(select id,name from stu where age < 20) a
inner join
(select sid,score from result where score < 60) b
on id= sid;- 聯合查詢:union | union all
select * from stu
union all
select * from teach;