SQL基礎語法複習
阿新 • • 發佈:2020-08-03
目錄
1. DML 資料操作指令
select 查
select 列 from 表 #取某列
select * from 表 #取全部
update 改
update 表 set 列=新值 where 列=某值 #更新列中某個值
update 表 set 列1=新值1, 列2=新值2 where 列=某值 #更新某一行中若干列
delete 刪
delete from 表 where 列=值 #刪除某行
delete from 表 #刪除所有行(不刪除表)
delete * from 表 #同上
insert into 增
insert into 表 values (值1,值2,...) #插入資料
insert into 表(列1,列2,...) values (值1,值2,...) #指定要插入的列
distinct 去重
select distinct 列 from 表
where 條件篩選
select 列 from 表 where 列 運算子 值 ## 多條件 select 列 from 表 where 列 運算子 值 and 列運算子 值 select 列 from 表 where 列 運算子 值 or 列運算子 值
order by 指定列結果排序
select 列1,列2 from 表 order by 列1 #預設升序asc
select 列1,列2 from 表 order by 列1 desc #降序
select 列1,列2,列3 from 表 order by 列1 asc, 列3 desc #先按1列升序,再按3列降序
編寫和執行順序
# 編寫順序
select...from...where...group by....having...order by
# 執行順序
from...where...group by...having ...select...order by
2. DDL 資料定義語言
資料庫相關操作
以下[name]
表示資料庫名稱。
show databases # 檢視資料庫列表
create database [name] # 建立新資料庫
show create databse [name] # 檢視資料庫詳細資訊
alter database [name] charset=編碼格式 #修改資料庫編碼格式
drop database [name] #刪除資料庫
資料表相關操作
以下[name]
表示表格名稱。
show tables #檢視當前資料庫下所有資料表
#建立新表,[]中內容可省略
create table 表名稱
(
列名稱1 資料型別[(最大位數) 約束], #文字、數字和日期/時間型別
列名稱2 資料型別[(最大位數) 約束],
列名稱3 資料型別[(最大位數) 約束],
...
) engine=引擎名稱, charset=編碼型別;
show create table [name] #查看錶的詳細資訊
desc [name] #查看錶的結構資訊
alter table [name] add 列名 資料型別 #表中新增列
alter table [name] drop column 列名 #刪除表中列
alter table [name] alter column 列名 資料型別 #修改表中列的資料型別
drop table [name] #刪除表
truncate table [name] #刪除表內容,但不刪除表本身
create index 索引名 on [name] (列1, 列2, ....) #在表中建立一個簡單索引(允許重複),列名規定要索引的列,列名後加desc表降序索引
create unique 索引名 on [name] (列1, 列2, ....) #在表中建立一個唯一索引
alter table [name] drop index 索引名 #刪除索引
Ref: SQL基本語法