《MySQL》MySQL教程
文章目錄
- 01 數據庫操作, 數據表操作
- 1. MySQL 服務管理
- 1.1 查看服務是否開啟
- 1.2 MySQL 服務管理命令
- 2. 連接數據庫
- 2.1 使用命令行客戶端連接
- 使用 mysql 命令連接數據庫
- 2.2 使用 Navicat 連接
- 3. 數據庫操作介紹
- 4. 數據庫操作
- 4.1 創建數據庫
- 4.2 修改數據庫編碼
- 4.3 顯示所有數據庫
- 4.4 切換、使用數據庫
- 4.5 顯示當前數據庫
- 4.6 刪除數據庫
- 5. 數據表操作
- 02 數據查詢
- 1. 導入數據
- 1.1 創建庫
- 1.2 選用庫
- 1.3 導入數據表
- 2. 單表查詢數據
- 2.1 查詢表中所有數據
- 2.2 查詢指定字段的顯示
- 2.3 as別名
- 2.4 消除重復數據 (group by可以結合聚合函數, 其功能更強大)
- 2.5 帶條件的查詢
- 2.5.1 比較運算符
- 2.5.2 邏輯運算符
- 2.5.3 模糊查詢
- 2.5.4 范圍查詢
- 2.5.5 空判斷
- 2.6 查詢結果排序
- 2.6.1 單字段排序
- 2.6.2 多字段排序
- 2.7 分頁查詢
- 2.8 聚合函數
- 2.9 分組
- 3. 多表查詢數據
- 3.1 普通多表查詢
- 3.2 多表查詢
- 3.3 表別名
- 3.4 內鏈接查詢
- 3.5 左連接查詢
- 3.6 右連接查詢
- 3.7 標量子查詢
- 3.8 列級子查詢
- 3.9 行級子查詢
- MySQL常用函數
- 時間和日期函數
- 數學函數
- 系統信息函數
- 其他函數
- sql時間
- MySQL日期數據類型、時間類型使用總結
- 一、MySQL 獲得當前日期時間 函數
- 二、MySQL 日期時間 Extract(選取) 函數。
- 三、MySQL 日期時間計算函數
- 四、MySQL 日期轉換函數、時間轉換函數
- 五、MySQL 時間戳(Timestamp)函數
- 六、MySQL 時區(timezone)轉換函數
01 數據庫操作, 數據表操作
1. MySQL 服務管理
1.1 查看服務是否開啟
ps aux | grep mysql1.2 MySQL 服務管理命令
啟動服務
sudo service mysql start停止服務
sudo service mysql stop重新啟動服務
sudo service mysql restart查看服務狀態
sudo service mysql status2. 連接數據庫
2.1 使用命令行客戶端連接
使用命令行客戶端連接, 連接數據庫需要知道主機,端口號,用戶名,密碼。。。
mysql -hlocalhost -p3306 -uroot -pmysql使用 mysql 命令連接數據庫
使用 mysql 命令連接數據庫,可以只指定用戶名和密碼,其它 使用默認
mysql -u root -p2.2 使用 Navicat 連接
cd xxx/navicat112_mysql_cs_x64/ ./start_navicat3. 數據庫操作介紹
在數據庫操作中,基本操作都是圍繞增刪改查來操作。簡稱CRUD
| C | Create | 創建 |
| R | Read/Retrieve | 查詢 |
| U | Update | 修改 |
| D | Delete | 刪除 |
4. 數據庫操作
4.1 創建數據庫
create database testdb; create database testdb2 character set utf8; show create database testdb;4.2 修改數據庫編碼
alter database testdb charset=utf8;4.3 顯示所有數據庫
show databases;4.4 切換、使用數據庫
use 數據庫名
use testdb;4.5 顯示當前數據庫
select database();4.6 刪除數據庫
drop database 數據庫名
drop database testdb2;5. 數據表操作
查看表
show tables;創建表
create table stu(sid int,sname char(20),sage int);顯示創建表信息
show create table stu;增加字段
alter table stu add gender char(4);刪除字段
alter table stu drop gender;修改字段的數據類型
alter table stu modify sname varchar(20);修改列的數據類型并且改名
alter table stu change sid snumber smallint;2.4.3 MySQL 常用字段類型
整數類型
小數類型
字符串類型
枚舉類型 enum(枚舉值1,枚舉值2,…)
enum('男','女')2.4.4 查詢數據
select * from stu;
2.4.5 插入數據
插入所有字段數據
insert into tStudent values(1,‘tom’,20)
插入指定字段
insert into stu(sage,sname) values(20,‘jack’);
插入多條數據
insert into stu values(2,‘rose’,20),(3,‘tony’,22);
更新所有的數據
update stu set sAge=25;
更新滿足條件的數據
update stu set sname=‘alice’ where name=‘tony’;
2.4.7 刪除數據
刪除全部數據 truncate
truncate stu;不需要加條件,也不能加條件,刪除全部數據,重置自動編號到默認值,沒有事務,速度快。
delete from stu;相當于 truncate stu,但是delete操作有事務操作,所以速度慢,而且不會重置自動編號
刪除滿足條件的數據
delete from stu where snumber = 1;
2.4.8 添加約束
添加約束的作用
約束是一種限制,它通過對表的行或列的數據做出限制,來確保表的數據的準確性,
完整性、唯一性,可靠性、聯動性
沒有對字段設置約束時的問題
數據冗余
失去數據完整性
數據缺少唯一標識
失去實體完整性
失去域完整性
失去引用完整性
數據庫常用約束
主鍵約束
create table tpk(id int primary key , name char(10));
自動增長
create table tai(id int auto_increment primary key,name varchar(10));
唯一性約束
create table tuni(id int unique,name char(10));
非空約束
create table tnn(id int,name char(10) not null);
默認約束
create table tdt(id int,name char(10) default ‘NoName’);
外鍵約束
– 表1
create table fClass(id int primary key,name char(10));
– 表2
create table fStudent(id int primary key auto_increment,
name char(10), cid int, foreign key(cid) references fClass(id));
設置外鍵約束字段所關聯的字段,必須是主鍵約束字段。想要刪除有設置外鍵的表,必須先刪除外鍵所關聯的表。檢查約束 (在MySQL中無效,不起作用)
create table tchk(id int,age int check(age > 0 and age < 150),gender char(10) check(‘boy’ or ‘girl’));
2.4.9 增加刪除約束
添加主鍵約束
alter table tpk add constraint PK_id primary key(id);
刪除主鍵約束
alter table tpk drop primary key;
添加外鍵約束
alter table tfk add constraint FK_id foreign key (id) references tpk(id);
刪除外鍵約束
alter table tfk drop foreign key FK_id;
2.4.10 數據庫導入導出
作用:使用數據庫和導入導出功能,可以對數據庫進行備份,遷移等操作。
導出數據庫
導出整個數據庫
mysqldump -uroot -p School > school_bak.sql
導出庫當中的指定表
mysqldump -uroot -p School tpk > tpk.sql
mysqldump -uroot -p School tpk tfk > tpktfk.sql
導入數據庫
導入數據庫前需要先創建一個空數據庫, 如sch
mysql -uroot -p sch < school_bak.sql
2.4.11 數據表設計思想
需求分析:根據用戶的需求,分析出需要記錄的數據
需求設計:根據分析出的數據,設計E-R模型圖 (Entity-Relationship,實體關系圖)
詳細設計:將E-R模型圖轉換成數據表
三大范式:使用數據庫三大范式的設計思想對數據表進行審核
第一范式 : 每一列都具有原子性,也就是不能再分割
第二范式 : 每個表只描述一件事情
第三范式 : 表中不能存在冗余字段
2.4.12 數據表練習
<創建數據庫 School>
create database School;
<創建學生表 tStudent>
tStudent學生表結構:
– sId – 學生編號 – sName – 姓名 – sAge – 年齡 – sGender – 性別 – sAddress-- 地址 –
sPhone – 電話 – sBirthday – 生日 – sCardId – 身份證號 – sClassId – 班級Id
答案:
create table tStudent(sId int,sName char(20),sAge tinyint,sGender enum(‘boy’,‘girl’),
sAddress varchar(50),sPhone char(11),sBirthday year,sCardId char(18),sClassid int);
<創建成績表 tScore>
TblScore成績表結構:
– sId(成績id,主鍵,自動編號) – sStuId(學生編號) – sEnglish(英語成績) – sMath(數學成績)
答案:
create table tScore(sid int unsigned auto_increment primary key, sStuId int, sEnglish float(5,2), smath float(5,2) );
<創建班級表 tClass>
tClass班級表結構:
– cId –班級ID – cName –班級名稱 – cDescription –班級描述 答案:
答案:
create table tClass(cId int,cName char(10),cDescription varchar(100));
<創建老師表tTeacher>
tTeacher老師表:
– tTId – tTName – tTGender – tTAge – tTSalary – tTBirthday
答案:
create table tTeacher(tId int, tName char(20),tAge tinyint,tGender enum(‘boy’,‘girl’),tSalary float(10,2),tBirthday year);
02 數據查詢
1. 導入數據
安裝并開啟MySQL數據庫服務
連接到數據庫
1.1 創建庫
create database db charset utf8;1.2 選用庫
use db;1.3 導入數據表
source /home/python/Desktop/school.sql2. 單表查詢數據
2.1 查詢表中所有數據
select * from t_students;2.2 查詢指定字段的顯示
select c_id,c_name,c_adress from t_student;2.3 as別名
select c_id as 學號,c_name as 姓名,c_adress 住址 from t_student;2.4 消除重復數據 (group by可以結合聚合函數, 其功能更強大)
select distinct c_adress from t_student;select distinct c_name,c_adress from t_student;2.5 帶條件的查詢
select * from t_student where c_gender="男";2.5.1 比較運算符
select * from t_student where c_age<20;2.5.2 邏輯運算符
select * from t_student where c_age<20 and c_gender="女";2.5.3 模糊查詢
select * from t_student where c_name like "孫";select * from t_student where c_name like "孫%";select * from t_student where c_name like "孫_";2.5.4 范圍查詢
select * from t_student where id in(1,3,8);select * from t_student where id between 2 and 5;2.5.5 空判斷
select * from t_student where c_age is null;select * fron t_student where c_age is not null;2.6 查詢結果排序
2.6.1 單字段排序
select * from t_student order by c_age;select * from t_student order by c_age asc;2.6.2 多字段排序
select * from t_student order by c_age desc,c_id asc,c_gender;2.7 分頁查詢
select * from t_student limit 3;select * from t_student limit 2,3;2.8 聚合函數
select sum(c_age) from t_student;select avg(c_age) from t_student;select max(c_age) from t_student where c_gender="男";select min(c_age) from t_student where c_gender="女";select count(*) from t_student;select dount(*) from t_student where c_gender="女";2.9 分組
-
單字段分組
select c_gender from t_student group by c_gender; -
多字段分組
select c_gender,c_adress from t_student group by c_gender,c_adress; -
group_concat()
select c_gender,group_concat(c_name) from t_student group by c_gender; -
分組和內聚函數使用
select c_gender,max(c_age),nin(c_age),sum(c_age),avg(c_age),count(c_age) from t_student group by c_gender;delect c_gender,max(c_age),min(c_age),sum(c_age),avg(c_age),count(c_age) from t_student group by c_gender; -
having條件子句
having作用和where類似, 用來對分組數據進行篩選
select c_gender,group_concat(c_name) from t_student where c_age>50 group by c_gender having c_gender="女";select c_gender,group_concat(c_name) from t_student where c_age>50 group by c_gender having c_gender="女";
where是對 “from 表” 中數據進行篩選
heving是對 “group by” 分組后的數據包進行篩選
因為在執行順序上, 在執行where時, 分組還沒有執行
得先根據where的條件取出數據, 才能對取出的數據進行分組. -
分組匯總(了解即可)
作用: 會在分組下方, 加一行, 顯示匯總
select c_gender from t_student group by c_gender with rollup;select c_gender,count(*) from t_student group by c_gender with rollup;
語法: with rollup
3. 多表查詢數據
3.1 普通多表查詢
select * from t_student,t_class; (無意義)3.2 多表查詢
select * from t_student,t_class where t_student.c_class_id = t_class.c_id;select t_student.name,t_student.c_name from t_student.c_3.3 表別名
select ts.c_name as "姓名", tc.c_name "班級名" from t_student as ts,t_class tc where ts.c_class_id = tc.c_id;3.4 內鏈接查詢
select ts.c_name,tc.c_name from t_student as ts inner join t_class tc on ts.c_class_id = tc.c_id;3.5 左連接查詢
select ts.c_name,tc.c_name from t_student as ts left join t_class tc on ts.c_class_id = tc.c_id;3.6 右連接查詢
select ts.c_name,tc.c_name from t_student as ts right jion t_class tc on ts.c_class_id = tc.c_id;3.7 標量子查詢
select * from t_srudent where c_age > (select avg(c_age) from t_stuent);3.8 列級子查詢
select * from t_student where c_id in (select c_class_id from t_student);3.9 行級子查詢
select * from t_student where(c_age,c_calss_id) = (select max(c_age),min(c_class_id) from t_student);MySQL常用函數
時間和日期函數
CURDATE 和 CURRENT_DATE:返回當前系統的日期值 CURTIME 和 CURRENT_TIME:返回當前系統的時間值 NOW 和 SYSDATE:返回當前系統的日期和時間值 UNIX_TIMESTAMP:獲取UNIX時間戳函數 FROM_UNIXTIME:將UNIX時間戳轉換為時間格式 MONTH:獲取指定日期中的月份 MONTHNAME:獲取指定日期中的月份英文名稱 DAYNAME:獲取指定日期對應的星期幾的英文名稱 DAYOFWEEK:獲取指定日期對應的一周的索引位置值 WEEK:獲取指定日期是一年中的第幾周 DAYOFYEAR:獲取指定日期是一年中的第幾天 DAYOFMONTH:獲取指定日期是一個月中的第幾天 YEAR:獲取年份,返回值范圍是1970~2069 TIME_TO_SEC:將時間參數轉換為秒數 DATE_ADD 和 ADDDATE:都是向日期添加指定的時間間隔 DATE_SUB 和 SUBDATE:都是向日期減去指定的時間間隔 ADDTIME:時間加法運算,在原始時間上添加指定的時間 SUBTIME:時間減法運算,在原始時間上減去指定的時間 DATEDIFF:獲取連個日期之間間隔 WEEKDAY:獲取指定日期在一周內的對應的工作日索引數學函數
ABS(x):返回x的絕對值 SIGN(x):返回x的符號 PI():返回圓周率π,默認顯示6位小數 SQRT(x):返回非負數的x的二次方根 MOD(x,y):返回x被y除后的余數 CEIL(x)、CEILING(x):返回不小于x的最小整數 FLOOR(x):返回不大于x的最大整數 EXP(x):返回e的x乘方后的值 LOG(x):返回x的自然對數,x相對于基數e的的對數 LOG10(x):返回x的基數為10的對數 RADIANS(x):返回x由角度轉化為弧度的值 CHAR_LENGTH(str):計算字符串字符個數 CONCAT(s1,s2,...):返回連接參數產生的字符串 CONCAT_WS(x,s1,s2,...):返回多個字符串拼接之后的字符串 LEFT(s,n):返回字符串s從最左邊開始的n個字符 RIGHT(s,n):返回字符串s從最右邊開始的n個字符 TRIM(s):返回字符串s刪除了兩邊空格之后的字符串 TRIM(s1 FROM s):刪除字符串s兩端所有子字符串s1 REPEAT(s,n):返回一個由重復字符串s組成的字符串 SPACE(n):返回一個由n個空格組成的字符串 REPLACE(s,s1,s2):返回一個字符串,用字符串s2代替字符串s中的所有字符串s1 SUBSTRING(s,n,len)、MID(s,n,len):從字符串s中返回一個,第n個字符串開始、長度為len的字符串 REVERSE(s):將字符串s反轉 ELT(n,str1,str2,str3,str4,...):返回第n個字符串系統信息函數
VERSION():查看MySQL版本號 CONNECTION_ID():查看當前用戶的連接數 USER()\CURRENT_USER()、SYSTEM_USER()、SESSION_USER():查看當前被MySQL服務器驗證的用戶名和主機的組合 CHARSET(str):查看字符串str使用的字符集 COLLATION():查看字符串排列方式其他函數
FORMAT(x,n):將數字x格式化 CONV(n,from_base,to_base):不同進制數之間的轉換 INET_ATON(expr):給出一個作為字符串的網絡地址的點地址 BENCHMARK(count,expr):重復執行count次表達式,expr用它在MySQL客戶端內部報告語句執行的時間 CONVERT(str USING charset):是哦那個字符集charset表示字符串strsql時間
MySQL日期數據類型、時間類型使用總結
MySQL 日期類型:日期格式、所占存儲空間、日期范圍 比較。
日期類型 存儲空間 日期格式 日期范圍 ------------ --------- --------------------- ----------------------------------------- datetime 8 bytes YYYY-MM-DD HH:MM:SS 1000-01-01 00:00:00 ~ 9999-12-31 23:59:59 timestamp 4 bytes YYYY-MM-DD HH:MM:SS 1970-01-01 00:00:01 ~ 2038 date 3 bytes YYYY-MM-DD 1000-01-01 ~ 9999-12-31 year 1 bytes YYYY 1901 ~ 2155在 MySQL 中創建表時,對照上面的表格,很容易就能選擇到合適自己的數據類型。不過到底是選擇 datetime 還是 timestamp,可能會有點犯難。這兩個日期時間類型各有優點:datetime 的日期范圍比較大;timestamp 所占存儲空間比較小,只是 datetime 的一半。
另外,timestamp 類型的列還有個特性:默認情況下,在 insert, update 數據時,timestamp 列會自動以當前時間(CURRENT_TIMESTAMP)填充/更新。“自動”的意思就是,你不去管它,MySQL 會替你去處理。
建表的代碼為:
create table t8 (`id1` timestamp NOT NULL default CURRENT_TIMESTAMP,`id2` datetime default NULL );一般情況下,我傾向于使用 datetime 日期類型。
兩者之間的比較:
2.timestamp比較受時區timezone的影響以及MYSQL版本和服務器的SQL MODE的影響.
MySQL 時間類型:時間格式、所占存儲空間、時間范圍。
時間類型 存儲空間 時間格式 時間范圍 ------------ --------- --------------------- ----------------------------------------- time 3 bytes HH:MM:SS -838:59:59 ~ 838:59:59time 時間范圍居然有這么大的范圍,特別是 time 可以取負值,有點奇怪。后來,看了 MySQL 手冊才知道這是為了滿足兩個日期時間相減才這樣設計的。
select timediff('2000:01:31 23:59:59', '2000:01:01 00:00:00'); -- 743:59:59 select timediff('2000:01:01 00:00:00', '2000:01:31 23:59:59'); -- -743:59:59 select timediff('23:59:59', '12:00:00'); -- 11:59:59注意,timediff 的兩個參數只能是 datetime/timestamp, time 類型的,并且這兩個參數類型要相同。即:datetime/timestamp 和 datetime/timestamp 比較;time 和 time 相比較。
雖然 MySQL 中的日期時間類型比較豐富,但遺憾的是,目前(2008-08-08)這些日期時間類型只能支持到秒級別,不支持毫秒、微秒。也沒有產生毫秒的函數。
《MySQL:MySQL日期數據類型、MySQL時間類型使用總結》適用于 MySQL 5.X 及以上版本。
一、MySQL 獲得當前日期時間 函數
1.1 獲得當前日期+時間(date + time)函數:now()
mysql> select now();+---------------------+ | now() | +---------------------+ | 2008-08-08 22:20:46 | +---------------------+除了 now() 函數能獲得當前的日期時間外,MySQL 中還有下面的函數:
current_timestamp() ,current_timestamp ,localtime() ,localtime ,localtimestamp -- (v4.0.6) ,localtimestamp() -- (v4.0.6)這些日期時間函數,都等同于 now()。鑒于 now() 函數簡短易記,建議總是使用 now() 來替代上面列出的函數。
1.2 獲得當前日期+時間(date + time)函數:sysdate()
sysdate() 日期時間函數跟 now() 類似,不同之處在于:now() 在執行開始時值就得到了, sysdate() 在函數執行時動態得到值??聪旅娴睦泳兔靼琢?#xff1a;
mysql> select now(), sleep(3), now();+---------------------+----------+---------------------+ | now() | sleep(3) | now() | +---------------------+----------+---------------------+ | 2008-08-08 22:28:21 | 0 | 2008-08-08 22:28:21 | +---------------------+----------+---------------------+mysql> select sysdate(), sleep(3), sysdate();+---------------------+----------+---------------------+ | sysdate() | sleep(3) | sysdate() | +---------------------+----------+---------------------+ | 2008-08-08 22:28:41 | 0 | 2008-08-08 22:28:44 | +---------------------+----------+---------------------+可以看到,雖然中途 sleep 3 秒,但 now() 函數兩次的時間值是相同的; sysdate() 函數兩次得到的時間值相差 3 秒。MySQL Manual 中是這樣描述 sysdate() 的:Return the time at which the function executes。
sysdate() 日期時間函數,一般情況下很少用到。
其中,下面的兩個日期函數等同于 curdate():
current_date() ,current_date其中,下面的兩個時間函數等同于 curtime():
current_time() ,current_time因為我國位于東八時區,所以本地時間 = UTC 時間 + 8 小時。UTC 時間在業務涉及多個國家和地區的時候,非常有用。
二、MySQL 日期時間 Extract(選取) 函數。
MySQL Extract() 函數除了沒有date(),time() 的功能外,其他功能一應具全。并且還具有選取‘day_microsecond’ 等功能。注意這里不是只選取 day 和 microsecond,而是從日期的 day 部分一直選取到 microsecond 部分。夠強悍的吧!
MySQL Extract() 函數唯一不好的地方在于:你需要多敲幾次鍵盤。
分別返回日期參數,在一周、一月、一年中的位置。
set @dt = '2008-08-08';select dayofweek(@dt); -- 6 select dayofmonth(@dt); -- 8 select dayofyear(@dt); -- 221日期 ‘2008-08-08’ 是一周中的第 6 天(1 = Sunday, 2 = Monday, …, 7 = Saturday);一月中的第 8 天;一年中的第 221 天。
MySQL week() 函數,可以有兩個參數,具體可看手冊。 weekofyear() 和 week() 一樣,都是計算“某天”是位于一年中的第幾周。 weekofyear(@dt) 等價于 week(@dt,3)。
MySQL weekday() 函數和 dayofweek() 類似,都是返回“某天”在一周中的位置。不同點在于參考的標準, weekday:(0 = Monday, 1 = Tuesday, …, 6 = Sunday); dayofweek:(1 = Sunday, 2 = Monday, …, 7 = Saturday)
MySQL yearweek() 函數,返回 year(2008) + week 位置(31)。
思考,如何返回中文的名稱呢?
MySQL last_day() 函數非常有用,比如我想得到當前月份中有多少天,可以這樣來計算:
mysql> select now(), day(last_day(now())) as days;+---------------------+------+ | now() | days | +---------------------+------+ | 2008-08-09 11:45:45 | 31 | +---------------------+------+三、MySQL 日期時間計算函數
MySQL adddate(), addtime()函數,可以用 date_add() 來替代。下面是 date_add() 實現 addtime() 功能示例:
mysql> set @dt = '2008-08-09 12:12:33';mysql> mysql> select date_add(@dt, interval '01:15:30' hour_second);+------------------------------------------------+ | date_add(@dt, interval '01:15:30' hour_second) | +------------------------------------------------+ | 2008-08-09 13:28:03 | +------------------------------------------------+mysql> select date_add(@dt, interval '1 01:15:30' day_second);+-------------------------------------------------+ | date_add(@dt, interval '1 01:15:30' day_second) | +-------------------------------------------------+ | 2008-08-10 13:28:03 | +-------------------------------------------------+date_add() 函數,分別為 @dt 增加了“1小時 15分 30秒” 和 “1天 1小時 15分 30秒”。建議:總是使用 date_add() 日期時間函數來替代 adddate(), addtime()。
MySQL 為日期減去一個時間間隔:date_sub()
mysql> select date_sub('1998-01-01 00:00:00', interval '1 1:1:1' day_second);+----------------------------------------------------------------+ | date_sub('1998-01-01 00:00:00', interval '1 1:1:1' day_second) | +----------------------------------------------------------------+ | 1997-12-30 22:58:59 | +----------------------------------------------------------------+MySQL date_sub() 日期時間函數 和 date_add() 用法一致,不再贅述。另外,MySQL 中還有兩個函數 subdate(), subtime(),建議,用 date_sub() 來替代。
函數參數“P” 的格式為“YYYYMM” 或者 “YYMM”,第二個參數“N” 表示增加或減去 N month(月)。
MySQL period_add(P,N):日期加/減去N月。
mysql> select period_add(200808,2), period_add(20080808,-2)+----------------------+-------------------------+ | period_add(200808,2) | period_add(20080808,-2) | +----------------------+-------------------------+ | 200810 | 20080806 | +----------------------+-------------------------+MySQL period_diff(P1,P2):日期 P1-P2,返回 N 個月。
mysql> select period_diff(200808, 200801);+-----------------------------+ | period_diff(200808, 200801) | +-----------------------------+ | 7 | +-----------------------------+在 MySQL 中,這兩個日期函數,一般情況下很少用到。
MySQL 日期、時間相減函數:datediff(date1,date2), timediff(time1,time2)
MySQL datediff(date1,date2):兩個日期相減 date1 - date2,返回天數。
MySQL timediff(time1,time2):兩個日期相減 time1 - time2,返回 time 差值。
select timediff('2008-08-08 08:08:08', '2008-08-08 00:00:00'); -- 08:08:08 select timediff('08:08:08', '00:00:00'); -- 08:08:08注意:timediff(time1,time2) 函數的兩個參數類型必須相同。
四、MySQL 日期轉換函數、時間轉換函數
可以看到,str_to_date(str,format) 轉換函數,可以把一些雜亂無章的字符串轉換為日期格式。另外,它也可以轉換為時間?!癴ormat” 可以參看 MySQL 手冊。
MySQL 日期、時間轉換函數:date_format(date,format), time_format(time,format) 能夠把一個日期/時間轉換成各種各樣的字符串格式。它是 str_to_date(str,format) 函數的 一個逆轉換。
MySQL get_format() 語法:
get_format(date|time|datetime, 'eur'|'usa'|'jis'|'iso'|'internal'MySQL get_format() 用法的全部示例:
select get_format(date,'usa') ; -- '%m.%d.%Y' select get_format(date,'jis') ; -- '%Y-%m-%d' select get_format(date,'iso') ; -- '%Y-%m-%d' select get_format(date,'eur') ; -- '%d.%m.%Y' select get_format(date,'internal') ; -- '%Y%m%d' select get_format(datetime,'usa') ; -- '%Y-%m-%d %H.%i.%s' select get_format(datetime,'jis') ; -- '%Y-%m-%d %H:%i:%s' select get_format(datetime,'iso') ; -- '%Y-%m-%d %H:%i:%s' select get_format(datetime,'eur') ; -- '%Y-%m-%d %H.%i.%s' select get_format(datetime,'internal') ; -- '%Y%m%d%H%i%s' select get_format(time,'usa') ; -- '%h:%i:%s %p' select get_format(time,'jis') ; -- '%H:%i:%s' select get_format(time,'iso') ; -- '%H:%i:%s' select get_format(time,'eur') ; -- '%H.%i.%s' select get_format(time,'internal') ; -- '%H%i%s'MySQL get_format() 函數在實際中用到機會的比較少。
五、MySQL 時間戳(Timestamp)函數
下面是示例:
select unix_timestamp(); -- 1218290027 ===得到當前時間的UNIX時間值將具體時間來轉換成timestamp
select unix_timestamp('2008-08-08'); -- 1218124800 select unix_timestamp('2008-08-08 12:30:00'); -- 1218169800將timestamp來轉換成具體時間
select from_unixtime(1218290027); -- '2008-08-09 21:53:47' select from_unixtime(1218124800); -- '2008-08-08 00:00:00' select from_unixtime(1218169800); -- '2008-08-08 12:30:00'select from_unixtime(1218169800, '%Y %D %M %h:%i:%s %x'); -- '2008 8th August 12:30:00 2008'請看示例部分:
select timestamp('2008-08-08'); -- 2008-08-08 00:00:00 select timestamp('2008-08-08 08:00:00', '01:01:01'); -- 2008-08-08 09:01:01 select timestamp('2008-08-08 08:00:00', '10 01:01:01'); -- 2008-08-18 09:01:01select timestampadd(day, 1, '2008-08-08 08:00:00'); -- 2008-08-09 08:00:00 select date_add('2008-08-08 08:00:00', interval 1 day); -- 2008-08-09 08:00:00MySQL timestampadd() 函數類似于 date_add()。
select timestampdiff(year,'2002-05-01','2001-01-01'); -- -1 select timestampdiff(day ,'2002-05-01','2001-01-01'); -- -485 select timestampdiff(hour,'2008-08-08 12:00:00','2008-08-08 00:00:00'); -- -12select datediff('2008-08-08 12:00:00', '2008-08-01 00:00:00'); -- 7MySQL timestampdiff() 函數就比 datediff() 功能強多了,datediff() 只能計算兩個日期(date)之間相差的天數。
六、MySQL 時區(timezone)轉換函數
convert_tz(dt,from_tz,to_tz)select convert_tz('2008-08-08 12:00:00', '+08:00', '+00:00'); -- 2008-08-08 04:00:00時區轉換也可以通過 date_add, date_sub, timestampadd 來實現。
select date_add('2008-08-08 12:00:00', interval -8 hour); -- 2008-08-08 04:00:00 select date_sub('2008-08-08 12:00:00', interval 8 hour); -- 2008-08-08 04:00:00 select timestampadd(hour, -8, '2008-08-08 12:00:00'); -- 2008-08-08 04:00:00總結
以上是生活随笔為你收集整理的《MySQL》MySQL教程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 地理信息系统基础知识
- 下一篇: 计算机专业毕业论文java毕业设计开题报