常見SQL語句(僅供自己複習)
DDL數據定義語言(表,庫,視圖…)
create drop alter show
增 刪 改 查
DML 數據操作語言
Insert delete update select
DCL 數據控制語句(權限)
grant revoke
1.啓動數據庫(linux系統下)
service mysqld start; 啓動 數據庫的服務
2.DDL語句
create 庫結構 表 視圖 觸發器 存儲過程
1.庫的操作:
create
create database [if not exists] 0623; 添加一個數據庫【不存在就創建】
drop
drop database [if exists] 0623; 刪除一個數據庫
use
use 0623;使用數據庫
show
show databases; 查看所有的庫
show create database 0623; 查看一個庫的創建信息
2.表的操作:
create table table_name(名字,類型,約束 [註釋])
create table stu( sid varchar(10),name varchar(20),sex enum (“man”,“woman”)); 創建一個表 括號(名字,類型,字段約束) 字段約束(主鍵(primary key) ,外鍵(foreign key), 唯一鍵 (UNIQUE),非空(not null),默認(default ))
desc stu 查看錶的字段信息
show create tables stu;查看創建時候表的字段信息
show tables; 查看所有的表
drop table stu; 刪除一個表
alter
1.字段類型 modify
alter table stu modify sid vachar(20); alter 表名 modify 字段名稱 類型
2.字段名稱 change
alter table stu change sid id vachar(20); 也可以修改字段類型
3.添加一個字段 add (after,first)
alter table stu add score float default 0; add +名稱+類型(放在最後一個)
alter table stu add score float default 0 after id; 放在after id後面 first 在…的前面
4.刪除字段 drop
alter table stu drop score; 刪除類型
5.修改表名 rename
alter table stu rename stua;
3.DML數據操作語句
insert delete update select
1.添加數據
insert into stu(表名) values(內容)(“001”,“張三”,“man”,20); 每次數據寫在()裏面用逗號隔開。 大批量 load
insert into stu(id,name,sex) values(“002”,”lisi”,”woman”); 當我們輸入的信息少於字段信息需要制定輸入的是某些字段信
2.刪除數據
delete from stu (where id = “006”); 刪除表的數據(限定條件)
3.修改數據
update stu set age = 19 (where id = “002”); 修改數據(指定條件 )
4.查詢數據
1.普通查詢
select * from stu;// 通匹查詢
select id , name,sec,age from stu; 查詢某些字段的信息
select * from stu where id = “001” ; 帶着過濾條件
2.去重查詢 distinct
select distinct age from table_name;
3.排序查詢 order by 升序 asc 降序 desc
select distinct age from stu order by age; 放在最後 不寫的話 默認升序
4. 分組查詢 group by (count 統計條數,year 年份)
select id,Sum(score) from result group by id; 根據 id 分組 sum 總分
5. 多表查詢
等值查詢
select stu.id,score from stu,result where stu.id = result.id and age < 20 and score < 60;(指明id 是哪的)
1.外連接查詢
1.左外連接查詢
select a.id,score
from (select id,age from stu where age < 20) a left join (select id, score from result where score < 60) b on a.id = b.id where b.score is not null;
2.右外連接查詢
select a.id,score from (select id,age from stu where age < 20) a right join
(select id,score from result where score < 60) b on a.id = b.id where a.id is not null;
3.全外連接查詢
select a.id,score from (select id,age from stu where age < 20) a full join
(select id,score from result where score < 60) b on a.id = b.id where a.id is not null;
2.內連接查詢
1.內連接查詢 只篩選匹配項
select a.id,score from (select id,age from stu where age < 20) a inner join
(select id,score from result where score < 60) b on a.id = b.id;
6.聚合查詢 union(去重) | union all (不去重)
select * from stu union select * from teach;