本文是個人自學過程中總結的SQL的基本使用,主要是基本的增刪改查,適合初學者。
sql的分類:
DDL:數據定義語言
操作對象:數據庫和表
關鍵詞:create alter drop
DML:數據操作語言
操作對象:記錄
DQL:數據查詢語言(非官方)
DCL:數據控制語言
操作對象:用戶 事務 權限
登錄數據庫:
mysql -uroot -p密碼
DDL:數據定義語言
操作對象:數據庫和表
關鍵詞:create alter drop
操作數據庫:
創建:
格式:
create database 數據庫名稱;
-- 創建數據庫時,設置數據庫的編碼方式
-- CHARACTER SET:指定數據庫採用的字符集,utf8不能寫成utf-8
-- COLLATE:指定數據庫字符集的排序規則,utf8的默認排序規則爲utf8_general_ci(通過show character set查看)
create database dbtest CHARACTER SET utf8 COLLATE utf8_general_ci;
刪除:
格式:
drop database 數據庫名稱;
修改數據庫編碼:
-- 修改數據庫編碼
alter database dbtest CHARACTER SET GBK COLLATE gbk_chinese_ci;
alter database dbtest CHARACTER SET utf8 COLLATE utf8_general_ci;
常用的命令:
查看所有的數據庫: show databases;
操作表:
1.創建表
格式:
create table 表名(字段描述,字段描述);
字段描述:
字段名稱 字段類型 [約束]
例如:
create table user(
id int primary key auto_increment,
username varchar(20)
);
create table user1(
id int primary key auto_increment,
username varchar(20)
);
-- 創建表時,設置表、字段編碼
use dbtest;
drop table if exists tbtest;
create table tbtest(
id int(10) auto_increment,
user_name varchar(60) CHARACTER SET GBK COLLATE gbk_chinese_ci,
email varchar(60),
PRIMARY key(id)
)CHARACTER SET utf8 COLLATE utf8_general_ci;
-- 修改表編碼
alter table tbtest character set utf8 COLLATE utf8_general_ci;
2.修改表
格式:
alter table 表名 ....
修改表名:
alter table 舊錶名 rename to 新表名;
例如:
alter table user1 rename to user10;
添加字段:
alter table 表名 add [column] 字段描述;
例如:
alter table user add password varchar(20);
修改字段名:
alter table 表名 change 字段名稱 新字段描述;
例如:
alter table user change password pwd varchar(20);
修改字段描述:
alter table 表名 modify 字段名稱 字段類型 [約束];
例如:
alter table user modify pwd int;
刪除字段:
alter table 表名 drop 字段名;
例如:
alter table user drop pwd;
修改字段編碼:
ALTER TABLE tbtest MODIFY email VARCHAR(60) CHARACTER SET utf8 COLLATE utf8_general_ci;
3.刪除表:
格式:
drop table 表名;
常用命令:
切換或者進入數據庫: use 數據庫名稱;
查看當前數據庫下所有表: show tables;
查看錶結構:desc 表名;
查看建表語句:show create table 表名;
查看所有的字符編碼:SHOW CHARACTER SET;
查看數據庫編碼:show variables like '%char%';
DML:數據操作語言
操作對象:記錄(行)
關鍵詞:insert update delete
1 插入:
格式1:
insert into 表名 values(字段值1,字段值2...,字段值n);
注意:
默認插入全部字段,
必須保證values後面的內容的類型和順序和表結構中的一致
若字段類型爲數字,可以省略引號
例如:
insert into user values(1,'tom');
insert into user values('2','tom');
insert into user values('3');-- 錯誤的
格式2:
insert into 表名(字段名,字段名1...) values(字段值,字段值1...);
注意:
插入指定的字段
必須保證values後面的內容的類型和順序和表名後面的字段的類型和順序保持一致.
例如:
insert into user (username,id) values('jack',4);
insert into user (username) values('jack',5);-- 錯誤的
2 修改:
格式:
update 表名 set 字段名=字段值,字段名1=字段值1... [where 條件];
例如:
update user set username='jerry' where username='jack';
3 刪除:
格式:
delete from 表名 [where 條件];
例如:
delete from user where id = '2';
DQL:數據查詢語言
關鍵詞:select
格式:
select ... from 表名 where 條件 group by 分組字段 having 條件 order by 排序字段 ase|desc
初始化環境:
-- 創建商品表
create table products(
pid int primary key auto_increment,
pname varchar(20),
price double,
pnum int,
cno int,
pdate timestamp
);
insert into products values (null,'泰國大榴蓮',98,12,1,null);
insert into products values (null,'新疆大棗',38,123,1,null);
insert into products values (null,'新疆切糕',68,50,2,null);
insert into products values (null,'十三香',10,200,3,null);
insert into products values (null,'老乾媽',20,180,3,null);
insert into products values (null,'豌豆黃',20,120,2,null);
練習:
簡單查詢:
練習:
1.查詢所有的商品
select * from products;
2.查詢商品名和商品價格.
-- 查看指定的字段
-- 格式: select 字段名1,字段名2 from 表名
select pname,price from products;
3.查詢所有商品都有那些價格.
-- 去重操作 distinct
-- 格式: select distinct 字段名,字段名2 from 表名
select price from products;
select distinct price from products;
4.將所有商品的價格+10元進行顯示.(別名)
-- 可以在查詢的結果之上進行運算,不影響數據庫中的值
-- 給列起別名 格式: 字段名 [as] 別名
select price+10 from products;
select price+10 新價格 from products;
select price+10 '新價格' from products;
select price+10 新 價 格 from products;-- 錯誤
select price+10 '新 價 格' from products;
select price+10 `新 價 格` from products;
條件查詢:
練習:
1.查詢商品名稱爲十三香的商品所有信息:
select * from products where pname = '十三香';
2.查詢商品價格>60元的所有的商品信息:
select * from products where price>60;
3.查詢商品名稱中包含”新”的商品
-- 模糊匹配
-- 格式: 字段名 like "匹配規則";
-- 匹配內容 %
"龍" 值爲龍
"%龍" 值以"龍"結尾
"龍%" 值以"龍"開頭
"%龍%" 值包含"龍"
-- 匹配個數 "__" 佔兩個位置
select * from products where pname like "%新%";
4.查詢價格爲38,68,98的商品
select * from products where price = 38 or price = 68 or price=98;
select * from products where price in(38,68,98);
where後的條件寫法:
* > ,<,=,>=,<=,<>,!=
* like 使用佔位符 _ 和 % _代表一個字符 %代表任意個字符.
* select * from product where pname like '%新%';
* in在某個範圍中獲得值.
* select * from product where pid in (2,5,8);
* between 較小值 and 較大值
select * from products where price between 50 and 70;
排序查詢:
1.查詢所有的商品,按價格進行排序.(asc-升序,desc-降序)
select * from products order by price desc;
2.查詢名稱有新的商品的信息並且按價格降序排序.
select * from products where pname like '%新%' order by price desc;
聚合函數:
對一列進行計算 返回值是一個,忽略null值
* sum(),avg(),max(),min(),count();
1.獲得所有商品的價格的總和:
select sum(price) from products;
2.獲得商品表中價格的平均數:
select avg(price) from products;
-- round(值,保留小數位)
select round(avg(price),2) from products;
3.獲得商品表中有多少條記錄:
select count(*) from products;
分組:使用group by
1.根據cno字段分組,分組後統計商品的個數,其實就是總條數.
select cno,count(*) from products group by cno;
2.根據cno分組,分組統計每組商品的總數量,並且總數量> 200;
select cno,sum(pnum) from products group by cno;
select cno,sum(pnum) from products group by cno having sum(pnum)>200;
注意:
where和having區別:
1.where 是對分組前的數據進行過濾 ;having 是對分組後的數據進行過濾
2.where 後面不能使用聚合函數,having可以
數據類型:
java mysql
byte tinyint
short smallint
int int(★)
long bigint
char/String varchar(★)|char
varchar:可變長度 mysql的方言 varchar(20): 存放abc 只會佔用三個
char:固定長度 char(20) 存放abc 佔用20個
boolean tinyint|int 代替
float|double float|double
注意:
double(5,2):該小數長度爲5個,小數佔2個 最大值:999.99
java.sql.Date date 日期
java.sql.Time time 時間
java.sql.Timestamp timestamp(★) 時間戳 若給定值爲null,數據庫會把當前的系統時間存放到數據庫中
datetime(★) 日期+時間
java.sql.Clob(長文本) mysql的方言(text)
java.sql.Blob(二進制) blob
約束
作用:
爲了保證數據的有效性和完整性
mysql中常用的約束:主鍵約束(primary key) 唯一約束(unique) 非空約束(not null) 外鍵約束(foreign key)
主鍵約束:被修飾過的字段唯一非空
注意:一張表只能有一個主鍵,這個主鍵可以包含多個字段
方式1:建表的同時添加約束 格式: 字段名稱 字段類型 primary key
方式2:建表的同時在約束區域添加約束
所有的字段聲明完成之後,就是約束區域了
格式: primary key(字段1,字段2)
create table pk01(
id int,
username varchar(20),
primary key (id)
);
insert into pk01 values(1,'tom');-- 成功
insert into pk01 values(1,'tom');-- 失敗 Duplicate entry '1' for key 'PRIMARY'
insert into pk01 values(null,'tom');-- 失敗 Column 'id' cannot be null
create table pk01(
id int primary key,
username varchar(20),
primary key (id)
);-- 錯誤的 一張表只能有一個主鍵
方式3:建表之後,通過修改表結構添加約束
create table pk02(
id int,
username varchar(20)
);
alter table pk02 add primary key(字段名1,字段名2..);
alter table pk02 add primary key(id,username);
insert into pk02 values(1,'tom');-- 成功
insert into pk02 values(1,'tomcat');-- 成功
insert into pk02 values(1,'tomcat');-- 失敗
唯一約束:
被修飾過的字段唯一,對null不起作用
方式1:建表的同時添加約束 格式: 字段名稱 字段類型 unique
create table un(
id int unique,
username varchar(20) unique
);
insert into un value(10,'tom');-- 成功
insert into un value(10,'jack');-- 錯誤 Duplicate entry '10' for key 'id'
insert into un value(null,'jack');-- 成功
insert into un value(null,'rose');-- 成功
方式2:建表的同時在約束區域添加約束
所有的字段聲明完成之後,就是約束區域了
unique(字段1,字段值2...)
方式3:建表之後,通過修改表結構添加約束
alter table 表名 add unique(字段1,字段2);-- 添加的聯合唯一
alter table 表名 add unique(字段1);-- 給一個添加唯一
alter table 表名 add unique(字段2);-- 給另一個添加唯一
create table un01(
id int,
username varchar(20)
);
alter table un01 add unique(id,username);
insert into un01 values(1,'tom');-- 成功
insert into un01 values(1,'jack');-- 成功
insert into un01 values(1,'tom');-- 失敗 Duplicate entry '1-tom' for key 'id'
非空約束
create table nn(
id int not null,
username varchar(20) not null
);
insert into nn values(null,'tom');-- 錯誤的 Column 'id' cannot be null
limit
limit可以提高效率,例如按照id查找用戶,確定只能查到一條,可以在最後加上limit 1,查到之後就不在查找了
case when
例如sex字段
CASE sex
WHEN '1' THEN '男'
WHEN '2' THEN '女'
ELSE '其他' END
ASE WHEN sex = '1' THEN '男'
WHEN sex = '2' THEN '女'
ELSE '其他' END
IFNULL
IFNULL(expr1,expr2)的用法:
假如expr1 不爲 NULL,則 IFNULL() 的返回值爲 expr1;
否則其返回值爲expr2。IFNULL()的返回值是數字或是字符串
例子
select (case when t1.main_mid = t13.mid then t13.id else t4.id end) as id,(case when t1.main_mid = t13.mid then t1.mid else t4.mid end ) as mid,t4.adxid,t4.tanxid,t4.saxid,t4.tadeid,t4.qaxid, t20.value as title,t21.value as description,t22.value as subimage,t23.value as oppoformatspec,
t4.adxadcategory,t4.tanxadcategory,t4.baiduadcategory,t4.tadeadcategory,t4.qaxadcategory,t4.amaxadcategory,
(case when t1.main_mid = t13.mid then t13.duration else t4.duration end) as duration, (case when t1.main_mid = t13.mid then t13.clicktype else t4.clicktype end) as clicktype,
t4.gdtadcategory,t4.youkuadcategory,t4.youkuid, t1.clickthrough, t1.clickurl, t1.autopause,
(case when t1.main_mid = t12.mid then t12.`value` else t8.`value` end) as CHANNEL_MID,(case when t1.main_mid = t15.mid then t15.`value` else t9.value end ) as CHANNEL_ADCATEGORY
from Adx.Ad3 t1
left join Adx.Plan t2 on t1.planid=t2.planid
left join Adx.AdxCertStatus t3 on t1.cid = t3.cid
left join Adx.Ad3ExtSetting t4 on t1.mid=t4.mid
left join Adx.Ad3KVSetting t5 on t1.mid = t5.mid and t5.name = 'OPPO_STATUS'
left join Adx.CustomerKVSetting t7 on t1.cid = t7.cid and t7.name = 'OPPO_CHANNELENABLE'
left join Adx.Ad3KVSetting t8 on t1.mid = t8.mid and t8.name = 'OPPO_MID'
left join Adx.Ad3KVSetting t9 on t1.mid = t9.mid and t9.name = 'OPPO_ADCATEGORY'
left join Adx.Ad3KVSetting t10 on t1.main_mid = t10.mid and t10.name = 'OPPO_STATUS'
left join Adx.Ad3KVSetting t12 on t1.main_mid = t12.mid and t12.name = 'OPPO_MID'
left join Adx.Ad3KVSetting t15 on t1.main_mid = t15.mid and t15.name = 'OPPO_ADCATEGORY'
left join Adx.Ad3ExtSetting t13 on t1.main_mid=t13.mid
left join Adx.Ad3KVSetting t20 on t1.mid = t20.mid and t20.name = 'TITLE'
left join Adx.Ad3KVSetting t21 on t1.mid = t21.mid and t21.name = 'DESCRIPTION'
left join Adx.Ad3KVSetting t22 on t1.mid = t22.mid and t22.name = 'SUBIMAGE'
left join Adx.Ad3KVSetting t23 on t1.mid = t23.mid and t23.name = 'OPPO_FORMAT_SPEC'
left join Adx.Ad2 t14 on t1.src2=t14.src2
left join Adx.Ad3KVSetting t11 on t1.mid = t11.mid and t11.name = 'OPPO_BIDENABLE'
left join Adx.Ad3KVSetting t16 on t1.main_mid = t16.mid and t16.name = 'OPPO_BIDENABLE'
where t3.autopause=0 and t1.autopause in (0,1) and t1.pause=0 and t2.pause=0 and t2.autopause=0
and now()>=IFNULL(t2.startdate,now()) and now()<=DATE_ADD(IFNULL(t2.enddate, now()), INTERVAL 1 DAY)
and (t5.value = '0' OR t10.`value` = '0')
and t1.syncflag=1 and t1.agauditstatus=0
and (t11.value = '1' or t16.`value` = '1')
and t7.value = '1'
and t14.pause=0 ;