常用SQL語句
SQL(Structure Query Language)結構化查詢語言用於關係型數據庫,Mysql,Oracle,sqlServer
前端學會這些基本的DB操作基本夠用了
DDL(Data Definition Language) 數據定義語言
包括:create(創建數據庫對象),alter(修改數據庫對象的結構)和drop(刪除數據庫對象)
- create(創建數據庫對象)
創建數據庫: CREATE DATABASE XXX;
創建數據庫表:
Create Table 表名(
列名1 數據類型 相關約束,
列名2 數據類型 相關約束,
....
列名n 數據類型 相關約束
)
CREATE TABLE `User` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`role` enum('admin','uploader','normal') DEFAULT 'uploader',
`name` varchar(255) DEFAULT NULL,
`created` int(11) unsigned NOT NULL,
`updated` int(11) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
alter(修改數據庫對象的結構)
-
添加列:Alter table 表名 add 列名 【數據類型 相關約束】 ;
alter table Users2 ADD test INT
- 刪除列:Alter table 表名 drop 列名 ;
alter table Users2 drop test
- 修改列: Alter table 表名 change 新 舊 數據類型 ;
alter table Users2 change test1 test2 int
- drop(刪除數據庫對象)
- 刪除表:Drop table 表名;
drop table "表格名
DML(Data ManipulationLanguage) 數據操縱語言
包括:Insert(插入數據),update(修改數據),delete(刪除數據)
- Insert 插入數據
- insert into table_name(列名1,列名2,…) values(‘值1’,‘值2’,…);
INSERT INTO `Users` (`id`, `role`)
VALUES
(1,'admin')
- Update 更新數據
- //更新某一行的某一列
update tableName set xxx=xxx where xxx=‘xxx’;
update Users1 set name = 'yuyang' where id = 2
- //更新某一行的若干列
update tableName set xxx=xxx,xxx=xx where xxx=‘xxx’ - Delete 刪除數據
- //刪除表中的某一行
delete from tableName where xxx=xxx
delete from Users1 where id=8;
- //刪除表中的所有數據
delete * from tableName;
DQL(Data Query Language) 數據查詢語言
格式:Select 字段列表|* from 表
select * from tableName
select id from tableName
- as 命別名
select * from tableName
- count 總數:
select count(*) from tableName
- sum 求和:
select sum(field1) from tableName
- avg 平均:
select avg(field1)from tableName
- max 最大:
select max(field1) from tableName
- min 最小:
select min(field1)from tableName
- 去重 distinct
select DISTINCT name from tableName
where 條件表達式(1=1)
select * from tableName where 1=1
- = >= < <=等運算符
select count(*) as count from tableName where id > 10
- and
select count(*) as count from tableName where id > 10 and name = 'yuyang'
- between … and
select * from Users where 1 and id not between 1 and 10 order by id asc
- or
select count(*) as count from tableName where id > 10 or name = 'yuyang'
- in
select * from tableName where id > 10 and name in ('yuyang','taozi')
- like 模糊查詢
- 1、%:表示任意0個或多個字符。可匹配任意類型和長度的字符,有些情況下若是中文,請使用兩個百分號(%%)表示 LIKE ‘%羽%’
select * from tableName where id > 10 and name like '%y%'
- _: 表示任意單個字符。匹配單個任意字符,它常用來限制表達式的字符長度語句 LIKE ‘三’
select * from tableName where id > 10 and name like 'yuyan_'
- 子查詢
select name from tableName where id in (select id from `Tags` where id > 4) select name from tableName where id=(select id from `Tags` where id = 4)
- 連接查詢
select Pic_Models.`ModelId`, Pic_Models.`PicId`,Pics.`src` from Pic_Models , Pics where Pic_Models.`PicId` = Pics.`id`
- order by 分組表達式
- ASC:升序
- DESC:降序
- limit 分頁表達式(limit );
select * from tableName LIMIT 10;–檢索前10行數據,顯示1-10條數據
select * from tableName LIMIT 1,10;–檢索從第2行開始,累加10條id記錄,共顯示id爲2…11