Mysql 基礎
/************
* 數據庫 *
************/
1.連接數據庫
mysql -u root -p
2.查看所有數據庫
show databases;
3.查看數據表
show tables;
4.查看要使用的某個數據庫(指定)
use + 數據庫名字;
5.創建數據庫名
create database 數據庫名字 charset=utf8;
6.刪除數據庫
drop database 數據庫名;
7.創建數據表
create table 表名(
id int(4),
name varchar(4),
sex char(4),
age int,
height char(4)
);
8.查看數據表中有哪些字段
desc 表名;
9.在數據表中插入數據
// 單挑插入信息
insert into 表名 values(1,'小強','男',23,176);
// 多條插入信息
insert into 表名(id,字段名稱a,字段名稱b,字段名稱c,字段名稱d)values(id,字段值a1,字段值b2,字段值c3,字段值d4),(id,字段值a2,字段值b2,字段值c2,字段值d2);
10.查看數據表有哪些信息
select * from 表名;
11.修改數據表里面的信息
// 修改單個字段信息
update 表名 set 字段名稱='要修改成的值' where id=要修改的id值;
// 修改多個字段信息
update 表名 set 字段名稱='要修改成的值',字段名稱='要修改成的值' where id='id是幾';
// 一個字段同時+1
update 表名 set 字段名稱=字段名稱+1;
12.刪除某個表中的一條信息
delete from 表名 where id=要刪除的id值;
13.刪除某個數據庫中的某個數據表
drop table 表名;
14.刪除數據庫名字0
drop database 數據庫名;
14.退出
exit;
/*******字段約束********/
15. 無符號 unsigned
// 創建一個數據表 unsigned 約束id不能為負數
create table 表名(
id int(10) unsigned,
name char(4),
sex char(4)
);
16.主鍵 primary key:這個字段的值必須是唯一的并且必須有值
// 創建一個數據表 設置主鍵?
// primary key (PRI)說明這個id字段是主鍵索引 并且本數據表中與這個主鍵id不能有相同的
create table 表名(
id int unsigned primary key,
name char(4),
sex char(4)
);
17.自增 auto_increment
// auto_increment id的自動增長
create table 表名(
id int unsigned primary key auto_increment,
name char(4),
sex cahr(4)
);
18.唯一 unique 值必須唯一 或者不給值 (不給值顯示NULL)
// 創建一個數據表
//? name后面的unique為這個字段的唯一
create table 表名(
id int unsigned primary key auto_increment,
name char(4) unique,
sex char(4)
) ;
19.默認值 default 如果不給定字段值 就默認一個值
// 創建一個數據表
// default 'nv' 給定默認值的方法
create table 表名(
id int unsigned primery key auto_increment,
name char(4) unique,
sex cahr(4) default 'nv'
);
20.不為空 not null? 值不能為空
// 創建一個數據表
// not null 如果沒有給值,int會轉為0,char會轉為空字符串
create table 表名(
id int unsigned primary key auto_increment,
name char(4) unique,
age int not null
);
21.int 類型id不會被截取
// 創建一個數據表
// int
create table 表名(
id int(4),
name char(4)
);
// 插入數據 id=123456會被全部插入數據表 name=abcdef只會插入4個字符abcd
insert into 表名(id,name) values(123456,abcdef);
22.零填充 zerofill 前導0填充 00001 0032 0003...
// 創建一個數據表
// zerofill當數組不夠4位時,用前導0填充? int(4)零填充后就是0001,0002...?
create table 表名(
id int(4) zerofill,
name char(4),
sex char(4)
);
/*********常用的數據類型**********/
23.整型 int
create table 表名(
id int unsigned primary key auto_increment,
age int
);
無符號 0 - 42億
有符號 -21億 - 21億
24.小整型 tinyint 占用一個字節
// 新建一個數據表
create table 表名(
id int unsigned primary key auto_increment,
age tinyint unsigned,
ages tinyint
);
無符號 0 - 255
有符號 -128 - 127
25.浮點 float(m,n)=float(6,2)=float(總位數,小數點后的位數)
// 新建一個數據表
// 如果這個值參與運算就會出現精度問題
create table 表名(
id int unsigned primary key auto_increment,
price float(6,2)
);
26.字符串浮點數 decimal(m,n) = decimal(總位數,小數點后的位數)
// 可以放心進行參與運算 使用deciml(m,n)
create table 表名(
id int unsigned primary key auto_increment,
price float(5,2),
prices deciml(5,2)
);
// float 123.46 = float 123.45 精度不準確
// decimal 123.46 = decimal 123.46 精度準確
(1) 定長字符串 char(n)? n代表幾個字符
‘abcd’實際占4個字符 寫幾個字符 就占幾個字節
存取效率高
char() 最長是255字符
(2) 變長字符串 varchar(n)? n代表幾個字符
‘abcd’實際占3個字符 不管寫幾個字符還是按實際字節占用? 用一個額外字節表示長度
更節省空間
varcahr() 最長是 21800字符左右 約小于等于 65535/3
(3) 枚舉字符串:enum多選一
enum('w','m','x','n','t'); 只能在這其中任意選一個 否則就為空 可以使用數值代替
enum('1','2','3','4','5'); 可以數值代替上面的內容結果一樣
//新建數據表 enum
create table 表名(
id int unsigned primary key auto_increment,
name char(4),
sex enum('男','女','未知','保密')
);
// 數值使用方法 將id為2的值改變成了x 因為數值3=x
update 表名 set sex=3 where id=2;
(4) 集合字符串:set多選多
set('w','r','t','o','d','g'); 只能在這個范圍內選取多個值 否則為空 可以使用數值代替
set('1','2','4','8','16','32'); 可以數值代替上面內容結果一樣 多選方法:例選擇15(數字相加) 就是選擇了 w r t o
// 新建數據表
create table 表名(
id int unsigned primary key auto_increment,
name char(4),
aihao set('電影','購物','睡覺','籃球','游戲','運動')
);
27.日期時間 detetime 8個字節 不能設置默認值
// 在php項目中 常用int類型來存儲時間戳
// 在mysql中,有timestamp這種類型 就叫時間戳
// mysql中一般使用的時間戳表達方式 created_at / updated_at
// 新建數據表 0000-9999年
create table 表名(
created_at datatime,
updated_at datetime
);
28.索引原理
建立索引
好處:能夠快速查詢到記錄
缺點:始終要調整 索引樹的平衡
添加 修改 刪除都需要調整索引樹
結論,當數據表中大量查詢操作,少量增刪改操作是,可以使用索引
什么樣的字段適合建立索引?
取值范圍大
取值要均勻
索引的種類:普通索引 主鍵索引 唯一索引 全文索引
1(23)
2(21) 4(34)
3(20) 6(22) 5(32) 11(40)
8(18) 7(26) 12(36)
10(17) 19(19) 13(27)
16(26)
29.事物
用戶名? ? 賬號金額
張三 100000
李四 10000
update 工資表 set 賬號金額=賬號金額+1000 where 用戶名=李四
update 工資表 set 賬號金額=賬號金額-1000 where 用戶名=張三
基本命令:
begin 開啟事物(記錄之后數據庫所有表中對記錄的操作)
commit 提交事物(確認之前所有記錄的操作)
rollback 撤銷回滾(撤銷begin之后所有對記錄的操作)
//新建一個數據表
create table 表名(
id int unsigned primary key auto_increment,
name char(4) unique,
sex enum('男','女') default '男',
age tinyint unsigned default 0,
classid char(6)
)ENGINE=MyISAM DEFAULT CHARSET=utf8;
1.begin 開啟事物
2.刪除一條信息? 修改一條信息
? 輸入命令:rollback 就會返回到原來的數據
3.commit 確認提交事物不可填入實際數據中
特性:SCID
原子性(Atomicity) 不可分割的完成一件事
一致性(Consistency) 要不都成功或者要不都失敗
隔離性(Isolation) 一件事情完成后再執行下一件事情
持久性(Durability) 如果事件提交后不可改變
表引擎:
只有InnoDB這種表引擎支持事物
create table users(
......
)engine=innodb;//多數是默認的
30.授權
//grant 可以使用的權限
//創建一個用戶允許的權限
grand 可以使用的權限 ON? ? 庫.表? ? TO '賬號'@'登錄地址' identified BY '密碼'
grant select,insert ON php217.users TO 'xxoo2'@'%' identified by '123456'
命令行:grant select,insert on php217.php3 to 'xxoo'@'%' identified by '123456';
flush privileges 確認授權
//刪除用戶
drop user '用戶名'@'%';
//mysql用戶表放在哪里?
......
//可以登錄到講師的服務器
mysql -h 192.168.217,250 -uxxoo -p123456 登錄到老師的mysql服務器
insert into users() 插入的你的名稱和年齡
31.生成sql語句
//新建一個數據表
create table 表名(
id int unsigned primary key auto_increment,
name char(4),
sex enum('w','n') default 'w',
age tinyint unsigned default 0,
classid char(6)
);
//php文件循環遍歷出數據
getsql.php
/*******************************************************
<?php
// 讀取文件信息
$str_name = file_get_contents('./names.txt');
// echo $str_name;
// 正則表達式 \S表示匹配非空白字符 +表示一次或者多次
$pth = '/\S+/';
// 進行匹配
preg_match_all($pth,$str_name,$arr);
// echo '<pre>';
// 隨機打亂數組
// shuffle($arr[0]);
// print_r($arr[0]);
// 準備一個字符串
$sql = 'insert into php4(name,sex,age,classid) values';
// 將有字段多選的值定義成數組
$arr_sex = ['w','m'];
$arr_classid = ['php217','php218','php219','php220','php221'];
// 循環遍歷數據
foreach($arr[0] as $name){
// 隨機出來一個性別 年齡 班級
$sex = $arr_sex[rand(0,1)];
$age = mt_rand(1,40);
$classid = $arr_classid[rand(0,4)];
// 拼接上面的$sql語句
$sql .= "('$name','$sex','$age','$classid'),";
}
//去掉最后的一個逗號
$sql = rtrim($sql,',');
echo $sql;
?>
//將打印出來的數據直接賦值到cmd命令行執行即可
*******************************************************/
names.txt
/******************************************************
陳澤鑫? 李永樺? 黃偉? 賀重陽? 徐文瑞? ? 孫傳飛? 蔣毅
崔松江? 金盛
閆菲 崔文志 林勇齊 夏星
陳同 謝聰 柴海清 王利楨
于兆林 田世成 張振宇 徐凱 姚忠鵬
張碩 盧天寅 劉世龍 趙晉平 李浩 侯雪鋒 劉喆
苑鵬剛 孫晨旭 龔亞桐 董嚴嚴 卓建法 王啟濤 楊坤城
楊佳鑫 梁世龍 丁佳根 劉亞琦 周炬成 朱少康 丁毅
丁立民 金宗坤 孫佳濤 郝睿哲 姚存智 孫曉美
郝帥 許相坤 韓家興 徐澳慶 安忠亮 張洋 盧雅麗
邊漢卿 曹宇 黃成蕊 史子旭 趙少猛 王小平 王艷艷
李博林 張森 何凱 付文濤 田非凡 陳松 楊雷
楊煦 黃熙康 孔凡昊 來鵬飛 佘浩陽 李彥鑫 柴曉航
李景磊 張立哲 馬子豪 張賀 王強強 肖慶虎
********************************************************/
32.命令行方式從數據庫中導入導出數據(31 的數據)
//導出
1.退出mysql
exit
2.mysqldum -u root -p php217 php4>d:/php4.sql
? 庫名字 表名? ? 導出的文件名
//導入
1.退出mysql
exit
2.mysql -u root -p php217 < d:/php4.sql
? 庫名稱? 文件位置和名稱
33.查詢練習
格式:
select[字段列表] | *
from 表名
where 搜索條件
group by 分組字段 [having子條件]
order by 排序 asc | desc
limit 分頁參數
注意:順序必須是這個順序
//一張表 名字為:stuphp
id? ? name? ? sex? ? age? ? classid
1? ? 張三? ? 男? ? ? 19? ? php217班
2? ? 李四? ? 女? ? ? 23? ? php218班
3? ? 王五? ? 男? ? ? 40? ? php219班
4? ? 趙六? ? 女? ? ? 45? ? php220班
5? ? 田七? ? 男? ? ? 34? ? php221班
6? ? 張九? ? 女? ? ? 22? ? php219班
//字段部分:
//顯示所有字段
select * from stuphp;
select * form 表名; (盡量不使用*)
//部分字段
select name,age from stuphp;
select 字段,字段 from 表名;
//查詢十年后的年齡
select name,age+10 from stuphp;?
select 字段,字段+10 from 表名;
//字段別名 給字段起別名(將字段名稱變好看一些)
select name,age+10 as ages from stuphp;
同上
select name,age+10 ages from stuphp;
//表別名
select name,age from stuphp as stuphps;
同上
select name,age from stuphp stuphps;
//字段合并(函數:concat() 年齡和性別合并在一起)
select name,concat(age,sex) from stuphp;
同上 '--'無意義就相當于 age~sex
select name,concat(age,'~',sex) from stuphp;
//去除重復的字段 (查看有幾個班級)
1.首先獲取班級信息
select calssid from stuphp;
2.去除重復 distinct
select distinct calssid from stuphp;
//在查詢結果中添加一列也就是添加一個字段(添加講師一列)
1.select *,'王老師' from stuphp;
2.將字段名稱更改一下
select *, '王老師' as '講師' from stuphp;
//條件部分: where
//某個字段的值等于什么(查詢php217的學生)
select * from stuphp where calssid='php217';
//多條件and查詢(php217的女生)
select * from stuphp where calssid='php217' and sex='w';
//年齡大于20歲的學生
select * from stuphp where age>20;
//年齡在30到40的人
select * from stuphp where age>=30 and age=<40;
同上 使用between(包括)
select * from stuphp where age between 30 and 40;
//年齡不在10到35之間的人
select * from stuphp where age<10 or age>35;
同上 使用not between
select * from stuphp where age not between 10 and 35;
//php217班和php218班的女生
select * from stuphp where (classid='php217' or classid='php218') and sex='w';
注意:和有時候應該是or 在mysql中and優先級比or高
//217班的男生和218班的女生
select * from stuphp where(classid='php217' and sex='m') or (classid='php218' and sex='w');
//找id為 3,5,8,9,12的人
select * from student where uid=3 or uid=5 or uid=8 or uid=9 or uid=12;
select * from stuphp where id in(3,5,8,9,12);
//找id不是3,5,8,9,12 的人
select * from stuphp where id not in(3,5,9,8,12);
//查詢classid值不為null的人
select * from studphp where classid is NULL;
? ? select * from studphp where classid is not NULL;
? ? //找名字為2個字的人 _代表一個字符 like
? ? select *? from stuphp where name like '__';
? ? //找名字中以 李 開頭的字 %代表0個到多個字符
? ? select * from stuphp where name like '李%';
? ? //找名字以 文 結尾的
? ? select * from? student where name like '%文';
? ? //找包含 旭 的人
? ? select * from student where name like '%旭%';
//分組查詢:
group by 分組伴隨著統計 男生多少 女生多少
//統計函數:
count(*) 統計個數 但是不會統計值為NULL的記錄
sum() 求和 比如符合條件的人的總年齡
avg() 平均和
max() 最大值
min() 最小值
//217總共多少人?
select conut(*) from stuphp where classid='php217';
//每個班人數
select classid,count(*) from stuphp group by classid;
//最大年齡 最小年齡 平均年齡
select max(age) from stuphp;
select min(age) from stuphp;
select avg(age) from stuphp;
//最大年齡 最小年齡 平均年齡 每個班的
select classid,max(age) from stuphp;
select classid,min(age) from stuphp;
select classid,avg(age) from stuphp;
//查找年齡最大的那個人
select * from stuphp where age=(select max(age) from student);
//查找在平均年齡之上的人
select * from stuphp where age>(select avg(age) from stuphp);
//每個班的男生,女生各多少人
select classid,sex,count(*) from stuphp group by classid,sex;
//每個班的男生女生各多少人,要求在20-30歲的
select classid,sex,count(*) from stuphp where age>=20 and age<=30 group by classid,sex;
//每個班多少人 只顯示班級人數大于16的
select classid,count(*) from php4 group by classid having count(*)>16
//按班級分組 并獲取每個班中學生的姓名
select classid,group_concat(name) from stuphp group by classid;
//排序
prder by 字段名 默認 asc升序 desc降序
//年齡從小到大的排序
select * from stuphp order by age asc;
select * from stuphp order by age;
//年齡從大到小
select * from stuphp order by age desc;
//先女后男 年齡再小到大? (先按性別排序 相同性別再按年齡排序)
select * from stuphp order by sex,age;
//先男后女
select * from stuphp order by sex,desc,age desc;
//先按班級排序 再按年齡從大到小
select * from stuphp order by classid,age desc;
/*******************************************/
//分頁查詢
//取出前5條記錄
select * from stuphp limi 5;
//跳過2條 顯示5條記錄
select * from stuphp limit 2,5;
第一頁:limit 0,5;
第二頁:limit 5,5;
第三頁:limit 10,5;
第四頁:limit 15,5;
第五頁:limit 20,5;
第 n頁:limit (n-1)*5,5;
//年齡最大的3個人(如果第3名和第4名年齡相同,取id最大的)
select * from stuphp order by age desc,id desc limit 3;
//218班女生年齡最小的3個人
select * from stuphp where class='php218' and sex='w' order by age limit 3;
//女生最多的班級
select classid,count(*) from stuphp where sex='w' group by classid order by count(*) desc limit 1;
/**********************************************************/
//多表聯查
數據庫名字:test
1.數據表:users
CREATE TABLE `users` (
? `uid` int(10) unsigned NOT NULL AUTO_INCREMENT,
? `uname` char(4) NOT NULL,
? `upwd` char(32) DEFAULT NULL,
? PRIMARY KEY (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
2.數據表:score
CREATE TABLE `score` (
? `uid` int(10) unsigned DEFAULT NULL,
? `yuwen` tinyint(3) unsigned DEFAULT NULL,
? `math` tinyint(3) unsigned DEFAULT NULL,
? `english` tinyint(3) unsigned DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3.數據表:details
CREATE TABLE `details` (
? `uid` int(10) unsigned DEFAULT NULL,
? `sex` enum('w','m','x') DEFAULT 'w',
? `age` tinyint(4) DEFAULT '0',
? `tel` varchar(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
//查詢2個表中的數據 (users details)
select * from users,details where users.uid=details.uid;
同上 別名
select * from users u,details d where u.uid=d.uid;
同上 INNER JOIN 內聯
select * from users u INNER JOIN details d ON u.uid=d.uid;
//查詢2個表中的數據 并且獲取到uid=5的信息
select * from users u,details d where u.uid=d.uid and u.uid=5;
同上 INNER JOIN 內聯
select * from users u INNER JOIN details d ON u.uid=d.uid where u.uid=5;
//左聯查詢 查詢學生信息表和成績表聯合起來 以左邊為主
select * from users u LEFT JOIN score s ON u.uid=s.uid;
//右連查詢 查詢學生信息表和成績表聯合起來 以右邊為主
select * from users u RIGHT JOIN score s ON u.uid=s,uid;
//不連 不進行聯合查詢拿到同樣的數據 效率也會很高
select * from users where uid=5;
select * from details where uid=5;