1.1、常用數(shù)據(jù)庫包括:Oracle、MySQL潮模、SQLServer编曼、DB2伤塌、SyBase等
1.2、Navicat for MySQL是一套專為MySQL設(shè)計的強(qiáng)大數(shù)據(jù)庫管理及開發(fā)工具
1.3、使用navicat for mysql連接MySQL服務(wù)(前提已安裝好xampp,啟動MySQL服務(wù)):
1.4鲸沮、連接上mysql服務(wù)后,選擇需要操作的數(shù)據(jù)庫->右鍵單擊->選擇“命令列界面”則可以進(jìn)行SQL編程或者直接在界面上進(jìn)行操作了
1.5锅论、mysql數(shù)據(jù)庫數(shù)據(jù)類型介紹
1.6讼溺、SQL分類:
DDL :數(shù)據(jù)定義語句(create alter drop)
DML :數(shù)據(jù)操作語句(insert update delete)
DQL :數(shù)據(jù)查詢語句(select)
DCL :數(shù)據(jù)控制語句(grant revoke commit rollback)
1.7、基本的邏輯語句
1.8最易、基本的sql語句:
1.8.1怒坯、數(shù)據(jù)庫操作
1、創(chuàng)建數(shù)據(jù)庫:
create database數(shù)據(jù)庫名稱;
2耘纱、查看有哪些數(shù)據(jù)庫:
show databases;
3敬肚、選擇使用數(shù)據(jù)庫;
use db1;
4、刪除數(shù)據(jù)庫:
drop database數(shù)據(jù)庫名;
1.8.2束析、對表操作
1、創(chuàng)建數(shù)據(jù)庫表:
use school;--選擇指定的數(shù)據(jù)庫憎亚,接下來的操作全部在這個庫中
如下:create table表名(表屬性列)员寇;
create table student(id int(4) primary key,name char(10) not null,sex char(2),age int(3));
其中:primary key --主鍵
not null --不為空
default --默認(rèn)值
auto_increment----自增
show tables;---查看有哪些表
desc user;---查看表結(jié)構(gòu)
2弄慰、刪除數(shù)據(jù)庫表
drop table表名;
如:drop table user;
3蝶锋、修改表
3.1修改表名:
alter table舊表名rename新表名陆爽;
alter table student rename user;
3.2修改表結(jié)構(gòu):
增加列add
alter table表名add增加的列名(數(shù)據(jù)類型、長度)扳缕;
alter table user add address char(10) not null;
3.3刪除列drop
alter table表名drop刪除的列名慌闭;
alter table user drop address;
3.4修改列change(注:屬性不可以為空,否則會出現(xiàn)錯誤提示)
alter table表名change修改列的列名 修改后的列名 (數(shù)據(jù)類型躯舔、長度)驴剔;
alter table user change age age int(4) not null;
alter table user change sex sex2 varchar(3) not null;
3.5刪除數(shù)據(jù)庫表:
drop table表名;
drop table class粥庄;----刪除class表格丧失;
1.8.3、對數(shù)據(jù)庫表中的數(shù)據(jù)操作
插入數(shù)據(jù):
1惜互、插入一條數(shù)據(jù)
insert into表名(屬性列)values(值)布讹;
以下三種方式:
a、insert into student(id,name,age) values(1,'lihui',20);
b训堆、insert into student values(2,'康夢霞',21);
----【值的順序和表結(jié)構(gòu)沒關(guān)系描验,只和插入數(shù)據(jù)屬性列的順序有關(guān)系;】
c坑鱼、insert into student(id,name) values(1,'lihui');
2膘流、插入多條數(shù)據(jù)
insert into student(id,name,age) values(6,'曹運(yùn)普',22),(7,'洪祖厚',23);
3、更新數(shù)據(jù):
update ..set ..
update表名set需要修改的值where語句姑躲;
update class set sex='boy' where id=2;
4睡扬、刪除數(shù)據(jù):全
delete from表名 (where語句);---根據(jù)條件選擇刪除
delete from表名黍析;----刪除部內(nèi)容卖怜,把數(shù)據(jù)庫清空了
truncate表名;---清空數(shù)據(jù)庫表=delete from表名阐枣;
如果在清空數(shù)據(jù)庫表時马靠,truncate效率更高,delete可以跟where語句蔼两,但是truncate不可以甩鳄;
5、查詢語句:
select * from表名额划;--- ?*代表所有列
select goods_name from ecshop妙啃;
運(yùn)算符:
算數(shù)運(yùn)算符+ - * /
比較運(yùn)算符>、=、<揖赴、!=馆匿、>=、<=
邏輯運(yùn)算符: and ?or not
select * from表名where語句燥滑;
5-1渐北、market_price和shop_price之和大于10000的商品信息,名稱和價格铭拧;
select goods_name,market_price,shop_price,market_price+shop_price from ecs_goods where market_price+shop_price>10000;
select goods_name,market_price,shop_price,market_price-shop_price from ecs_goods wheremarket_price-shop_price>1000;
5-2商品的數(shù)量大于等于97的商品有哪些赃蛛?
select goods_name,goods_number from ecs_goods wheregoods_number>=97;
5-3預(yù)售額大于100000商品信息
select goods_name,shop_price*goods_number from ecs_goods whereshop_price*goods_number>100000;
5-4商品數(shù)量大于97并且價格大于5000的商品信息,展示名稱和價格搀菩,數(shù)量呕臂;
select goods_name,goods_number,shop_price from ecs_goods wheregoods_number>97 and shop_price>5000;
5-5商品是熱銷的產(chǎn)品或者數(shù)量小于99的商品信息 名稱,熱銷is_hot=1秕磷,數(shù)量
select goods_number from ecs_goods wherenot goods_number=99;
select goods_number from ecs_goods wheregoods_number!=99;
Mysql表內(nèi)容查詢:
1诵闭、between....and....(在小數(shù)和大數(shù)之間:注意包含邊界值含=)
用法:select要顯示的信息1,要顯示的信息2 from表名where要求的信息between...and...;
2、limit(查詢行數(shù)從當(dāng)前行下一行開始顯示)
Limit當(dāng)前所在行,所顯示行數(shù)
用法:select * from表名limit當(dāng)前所在行,所顯示行數(shù);
3澎嚣、like(模糊查詢)(注:要查詢字段在第一個或者最后一個位置%可以只寫一個疏尿,一般是寫兩個一個在前一個在后)
%匹配所有字符-匹配單個字符
用法:select * from student where Department='計算機(jī)系' andName like '張%';
或者select * from student where Department='計算機(jī)系' andName like '張__';(_有兩個代表張后面有連個字符)
Mysql函數(shù):(以下1-7都可以和where語句結(jié)合查詢更為具體的條件信息)
1、Count(計數(shù)即統(tǒng)計)
select count(*) from score;
2易桃、Sum(求和)
select sum (Grade) from score;
3褥琐、max(求最大值)
select max(Grade) from score;
4、min(求最小值)
select min(Grade) from score;
5晤郑、avg(求均值)
select avg(Grade) from score;
select avg(Grade) from scorewhere C_name='計算機(jī)';
6敌呈、distinct(去重)
selectdistinctshop_price from ecs_goods;
7、mod(求余可以算作運(yùn)算符)
select goods_name from ecs_goods wheregoods_number mod 5=2;
8造寝、排序:以下兩個都可以和limit連用
order by(升序排序)
Order by....desc(降序排序)
selectgoods_name,shop_price from ecs_goodsorder by shop_price desc limit 0,3;
select stu_id,grade from score where c_name='中文' and grade<(select avg(grade) from score) order bygrade desc;(忘記寫好幾次磕洪,執(zhí)行不出來)
select stu_id,grade from score ?where grade<(select avg(grade) from score where c_name='計算機(jī)') order by grade desc;(where的嵌套注意()的位置)
9、分組:注意和排序order by的區(qū)別
group by一般是先對什么進(jìn)行分組诫龙,在進(jìn)行統(tǒng)計操作
select max(grade),c_name from score group by c_name;
10析显、條件語句having(注意和where的區(qū)別)
select sum(grade) from score group by c_name havingsum(grade)>200;
Having是在分組之后加的條件,where是在分組之前加的條件
where......group by......having.....order(使用順序規(guī)律)
select c_name,count(*) from score group by c_name having count(*)>=2;(求某一科目學(xué)生人數(shù)不小于2的)(注意count(*)的用法)
9签赃、多表查詢
需要建立一個連接多表連接
主鍵與外鍵
用戶表user_id當(dāng)成主鍵 外鍵esc_order_info ?user_id
查詢出那些用戶存在訂單信息谷异,顯示用戶名跟訂單號
select order_id,user_name from ecs_order_info,ecs_users where ecs_order_info.user_id=ecs_users.user_id;
查詢出訂單的金額,用戶名锦聊,產(chǎn)品名稱
select c1.goods_name,c1.goods_price,u1.user_name from ecs_order_goods c1,ecs_order_info c2,ecs_users u1 where c1.order_id=c2.order_id and c2.user_id=u1.user_id;
//1歹嘹,from表中逗號隔開2,where條件后列出表與表的關(guān)聯(lián)孔庭,多個表中and連接3尺上,ecs_order_goods c1取表的別名
//4,展示的值全部在from前面,當(dāng)多個表中存在相同的列名時尖昏,必須添加表的前綴
取表的別名
10仰税、union合并
select * from student UNION select * from student_copy;
//把student與student_copy表的結(jié)果展示一起
//2張表中存在重復(fù)時候构资,去重
//2張表中存在的列數(shù)量要一致
select id,name from student UNION select name,age from student_copy UNION select stu_id,score from sc;
select * from student,sc where student.id=sc.stu_id;//多表查詢只展示了2張表相同部分
11抽诉、左右連接
left join左連接
right join右連接
//左表為基準(zhǔn),右表的數(shù)據(jù)依附左表,左表數(shù)據(jù)全部展示吐绵,當(dāng)右邊存在可以相同連接時展示對應(yīng)
//當(dāng)左表中存在迹淌,右表中不存在數(shù)據(jù)時,右表列用null代替
//當(dāng)右邊存在左表不存在數(shù)據(jù)時己单,刪掉
SELECT * from student left JOIN sc on student.id=sc.stu_id;
right join右連接//與左連接反之
SELECT * from student right JOIN sc on student.id=sc.stu_id;
12唉窃、join內(nèi)連接//
只展示相同數(shù)據(jù)部分
SELECT * from student JOIN sc on student.id=sc.stu_id;
oracl full join全連接//mysql數(shù)據(jù)沒有全連接
仿照全連接
SELECT * from student left JOIN sc on student.id=sc.stu_id UNION SELECT * from student RIGHT JOIN sc on student.id=sc.stu_id;
13、創(chuàng)建視圖
create view視圖名as select語句
查看創(chuàng)建視圖的語句:show create view viewname;
刪除視圖:drop view視圖名
create view productcustomers as select cust_name纹笼,cust_contact,prod_id from customers纹份,orders,orderitems where customers.cust_id=orders.cust_id and orderitems.order_num=order.order_num ;
//創(chuàng)建了一個名為productcustomers的視圖廷痘,它聯(lián)結(jié)3個表蔓涧,以返回訂購了任意產(chǎn)品的所有客戶列表,如果執(zhí)行select * from productcustomers ,將列出訂購了任意產(chǎn)品的客戶笋额。
為了檢索出訂購了產(chǎn)品tnt2的客戶元暴,則
select cust_name,cust_contact from productcustomers ?where prod_id='tnt2';
14、備份恢復(fù)常用方法
MySQL有三種保證數(shù)據(jù)安全的方法:
l常規(guī)日志和更新日志通過保存執(zhí)行的查詢供你必要時恢復(fù)
l數(shù)據(jù)庫備份通過導(dǎo)出數(shù)據(jù)或者表文件的拷貝來保護(hù)數(shù)據(jù)
l數(shù)據(jù)庫復(fù)制
MySQL內(nèi)部復(fù)制功能是建立在兩個或兩個以上服務(wù)器之間兄猩,通過設(shè)定它們之間的主-從關(guān)系來實現(xiàn)的茉盏。其中一個作為主服務(wù)器,其它的作為從服務(wù)器枢冤。
用SQL進(jìn)行備份恢復(fù)語句
備份(在MySQL的bin目錄下命令行中執(zhí)行):
mysqldump -u root -p database_name > d:\db.bak
恢復(fù)(同樣在mysql的bin目錄下執(zhí)行):
mysql -u root -p database_name < d:\db.bak
注意:在WIN下,路徑用path/filename.sql是不行的,那就用path\filename.sql
15鸠姨、時間日期函數(shù)
1、獲得當(dāng)前日期時間函數(shù)
a淹真、獲得當(dāng)前日期+時間(date+time)函數(shù):now()
mysql>select now();
| now() |
| 2017-05-08 22:20:46 |
b讶迁、獲得當(dāng)前日期+時間(date+time)函數(shù):sysdate()
mysql>select sysdate();
| sysdate() ??????????|
| 2017-05-17 11:24:34 |
sysdate()日期時間函數(shù)跟now()類似,不同之處在于:now()在執(zhí)行開始時值就得到了趟咆,sysdate()在函數(shù)執(zhí)行時動態(tài)得到值添瓷。看下面的例子就明白了:
mysql> select now(),sleep(3),now();
| now() ??????????????| sleep(3) | now() ??????????????|
| 2017-05-17 11:20:19 | ???????0 | 2017-05-17 11:20:19 |
mysql> select sysdate(),sleep(3),sysdate();
| sysdate() ??????????| sleep(3) | sysdate() ??????????|
| 2017-05-17 11:25:46 | ???????0 | 2017-05-17 11:25:49 |
sysdate()日期時間函數(shù)值纱,一般情況下很少用到鳞贷。
c、獲得當(dāng)前時間戳函數(shù):current_timestamp,current_timestamp();
mysql>select current_timestamp,current_timestamp();
| current_timestamp ??| current_timestamp() |
| 2017-05-17 11:30:16 | 2017-05-17 11:30:16 |
16虐唠、日期轉(zhuǎn)換函數(shù)搀愧、時間轉(zhuǎn)換函數(shù)
a、Date/Time to Str(日期/時間轉(zhuǎn)換為字符串)函數(shù):date_format(date,format), time_format(time,format)
mysql> select date_format('2008-08-08 22:23:01', '%Y%m%d%H%i%s');
| date_format('2008-08-08 22:23:01', '%Y%m%d%H%i%s') |
| 20080808222301 ????????????????????????????????????|
以上例子日期、時間轉(zhuǎn)換函數(shù)能夠把一個日期/時間轉(zhuǎn)換成各種各樣的字符串格式咱筛。它是str_to_date(str,format)函數(shù)的 一個逆轉(zhuǎn)換搓幌。
b、Str to Date(字符串轉(zhuǎn)換為日期)函數(shù):str_to_date(str, format)
select str_to_date('08/09/2008', '%m/%d/%Y'); -- 2008-08-09
select str_to_date('08/09/08' , '%m/%d/%y'); -- 2008-08-09
select str_to_date('08.09.2008', '%m.%d.%Y'); -- 2008-08-09
select str_to_date('08:09:30', '%h:%i:%s'); -- 08:09:30
select str_to_date('08.09.2008 08:09:30', '%m.%d.%Y %h:%i:%s'); -- 2008-08-09 08:09:30
c迅箩、(日期溉愁、天數(shù))轉(zhuǎn)換函數(shù):to_days(date), from_days(days)
mysql> select to_days('2008-08-08');
| to_days('2008-08-08') |
| ???????????????733627 |
mysql> select from_days('733627');
| from_days('733627') |
| 2008-08-08 ?????????|
1row in set
d、(時間饲趋、秒)轉(zhuǎn)換函數(shù):time_to_sec(time), sec_to_time(seconds)
select time_to_sec('01:00:05'); -- 3605
select sec_to_time(3605); -- '01:00:05'
e拐揭、拼湊日期、時間函數(shù):makdedate(year,dayofyear), maketime(hour,minute,second)
select makedate(2001,31); -- '2001-01-31'
select makedate(2001,32); -- '2001-02-01'
mysql> select maketime(12,15,30);
| maketime(12,15,30) |
| 12:15:30 ??????????|
mysql> select maketime(30,70,120);
| maketime(30,70,120) |
| NULL ???????????????|輸入數(shù)據(jù)不合法輸出為空值
17奕塑、日期時間計算函數(shù)
a堂污、為日期增加一個時間間隔:date_add()
set @dt = now();
select date_add(@dt, interval 1 day);
mysql> set @dt = now();
Query OK, 0 rows affected
mysql> select date_add(@dt, interval 1 day);
+-------------------------------+
| date_add(@dt, interval 1 day) |
+-------------------------------+
| 2017-05-18 14:09:13 ??????????|
+-------------------------------+
select date_add(@dt, interval 1 hour); -- add 1 hour
select date_add(@dt, interval 1 minute);
select date_add(@dt, interval 1 second);
select date_add(@dt, interval 1 microsecond);
select date_add(@dt, interval 1 week);
select date_add(@dt, interval 1 month);
select date_add(@dt, interval 1 quarter);
select date_add(@dt, interval 1 year);
select date_add(@dt, interval -1 day); -- sub 1 day
b、adddate龄砰,addtime函數(shù)可以用date_add來替代盟猖,如下
mysql> set @dt = '2008-08-09 12:12:33';
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 |
+-------------------------------------------------+
c、為日期減去一個時間間隔: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()日期時間函數(shù) 和date_add()用法一致换棚,不再贅述
d式镐、日期、時間相減函數(shù):datediff(date1,date2), timediff(time1,time2)
MySQL datediff(date1,date2):兩個日期相減date1 - date2圃泡,返回天數(shù)碟案。
mysql> select datediff('2008-08-08', '2008-08-01');
+--------------------------------------+
| datediff('2008-08-08', '2008-08-01') |
+--------------------------------------+
| ???????????????????????????????????7 |
+--------------------------------------+
select datediff('2008-08-01', '2008-08-08'); -- -7
MySQL timediff(time1,time2):兩個日期相減time1 - time2,返回time差值颇蜡。
mysql> select timediff('2008-08-08 08:08:08', '2008-08-08 00:00:00');
+--------------------------------------------------------+
| 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)函數(shù)的兩個參數(shù)類型必須相同价说。
e、 時間戳(timestamp)轉(zhuǎn)換风秤、增鳖目、減函數(shù):
timestamp(date) -- date to timestamp
timestamp(dt,time) -- dt + time
timestampadd(unit,interval,datetime_expr) --
timestampdiff(unit,datetime_expr1,datetime_expr2) --
示例:
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:01
select 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:00
MySQL timestampadd()函數(shù)類似于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'); -- -12
select datediff('2008-08-08 12:00:00', '2008-08-01 00:00:00'); -- 7
MySQL timestampdiff()函數(shù)就比datediff()功能強(qiáng)多了缤弦,datediff()只能計算兩個日期(date)之間相差的天數(shù)领迈。