1. 程式人生 > >MYSQL資料庫基本操作和命令詳解

MYSQL資料庫基本操作和命令詳解

在學習MySQL資料庫之前我們要知道MySQL資料庫的操作語言的分類;

  • DDL(資料定義語言) 表的定義、使用者的定義… create drop alter
  • DML(資料操控語言) 對資料的增加、修改、刪除、查詢 insert update delete select
  • DCL(資料控制語言) grant(授權) revoke(回收)

資料庫基本操作

1. DDL 資料定義語言

  1. 建庫相關操作
    設定預設的字元編碼

一種是在建庫語句上帶上字元編碼
另一種是在啟動服務時新增配置檔案
我們知道utf-8是我們平時表示漢字的常用字元編碼,所以我麼在建立資料庫時就必須先設定它能識別和儲存的字元編碼;
建庫SQL語句(在mysql提示符下執行)

create database 資料庫名 character set utf8mb4;

mysql中的utf8字元不夠完整,utf8mb4是完整版本的

刪除資料庫

drop database 資料庫名;

檢視建庫資訊

show create database 資料庫名;

要修改全域性的設定,在mysql解壓目錄新增 my.ini 配置檔案,在其中輸入(推薦)

[mysqld]
character-set-server=utf8mb4

這裡注意我們在安裝目錄下寫入了配置檔案後,如果想要它生效,就必須刪除我們之前安裝的MySQL服務,然後重新安裝伺服器端mysqld,這樣配置檔案才能生效;
停止舊服務,刪除舊服務,安裝新服務,啟動新服務

net stop mysql
sc delete mysql
mysqld install
net start mysql
  • 建表(table)
    一個庫中有多張表,每張表裡有多條資料
    表分成行(row 橫向)與列(column 縱向)

    學號 姓名 性別
    1 張三 男
    2 李四 女

  1. 選庫
    use 庫名;
  2. 建表
create table 表名(1名 型別,2名 型別,
    ...
);
create table student(
    id int,
    name varchar(10),
    sex char
(1) );
  • 建表所需資料型別介紹:
    整數型別: tinyint(1個位元組), smallint(2個位元組), int(4個位元組), bigint(8個位元組)
    無符號數字 tinyint unsigned (0~255)

    浮點型別: float, double
    定點小數: decimal(總位數, 小數位數)
    decimal(10, 2) 小數部分兩位,整數部分最大8位

    字元型別
    char(長度) char(10) 表示最多存10個字元, 定長,效率高
    varchar(長度) varchar(10) 表示最多儲存10個字元,變長

    “abc” "abc " 儲存時,長度不足,用空格補齊
    “abc” “abc” 儲存時,根據實際長度儲存,可以節省空間
    日期型別
    datetime
    timestamp

  1. 插入資料
insert into 表名(1,2, ... 列n) values (1,2, ... 值n);

注意:值個數要與列個數一致

insert into student(id,name,sex) values(1, '張三', '男');
  1. 查詢資料
    語法:
select1,2, ... from 表名;
select id, name, sex from student;
  1. 檢視所有庫
show databases;
  1. 檢視所有表
show tables;
  1. 唯一主鍵
    每張表只能有一個主鍵 primary key
    主鍵的值必須是唯一,且非空的
create table 表名(1名 型別 primary key,2名 型別,
    ...
);

刪表語法:drop table 表名;

create table student(
    id int primary key,
    name varchar(10),
    sex char(1)
);

insert into student(id,name,sex) values(null, ‘李四’, ‘男’);

自增列,用來解決主鍵衝突問題
在主鍵列後加入:auto_increment
1 2 3 4 …
因為id列由資料庫維護,所以有了自增列後就不需要給id列賦值了

create table student(
    id int primary key auto_increment,
    name varchar(10),
    sex char(1)
);

修改表語法:

alter table... (新增列, 修改列, 刪除列, 重新命名列8.0才有)

一次插入多條記錄(mysql獨有)
insert into student(name,sex) values(‘李四’, ‘男’),(‘王五’, ‘男’),(‘趙柳’, ‘男’);

  1. 查詢所有列
    select * from student;
    mysql會把*翻譯成:id,name,sex

  2. 刪除記錄(只刪除資料,不刪表)

delete fromwhere 條件;
  1. 刪除表(連表和資料一塊刪除)
drop table;

只刪除id=6的記錄
delete from student where id=6;

  1. 新增列
    語法:alter table 表名 add 列名 資料型別;
    例如:給student新增一個age列
alter table stduent add age tinyint unsigned;
  1. 修改列
    語法:alter table 表名 modify 列名 新型別;
    例如要修改列的長度定義原來varchar(10)
alter table student modify name varchar(20);
  1. 刪除列
    語法:alter table 表名 drop 列名;

  2. 重新命名列
    語法:alter table 表名 rename column 舊列名 to 新列名;

2. DML (資料操控語言) (重點)

insert

語法1:

insert into 表名(...) values(...);  插入一行

語法2:

insert into 表名(...) values(...), (...), (...), (...);  插入多行
create table student2(
    id int primary key,
    name varchar(20),
    sex char(1)
);

語法3:從表1查詢,把查詢結果插入表2

insert into2 select * from1;

如果兩張表結構不一樣,可以在select後加具體的列名,以便和新表的列相匹配
例如:

create table student3(
    id int primary key,
    name varchar(20)
);
insert into student3 select id,name from student;

load data

可以把外部文字檔案的內容匯入到資料庫表中
語法:load data infile ‘檔案路徑\檔名字’ into table 表名;

create table hero(
    id int primary key,
    name varchar(10),
    loc varchar(10),
    sex char(1),
    birth int,
    death int,
    power int
);

要讓load data命令生效,必須修改設定:

[mysqld]
character-set-server=utf8mb4
secure-file-priv=

其中secure-file-priv預設是null值,表示不允許載入檔案
可以改為具體目錄名,表示只能從這個目錄載入檔案
如果改為"",表示可以從任意目錄載入檔案

例如:載入之前heroes.txt,把資料存入hero:

load data infile 'e:\\heroes.txt' into table hero;

如果檔案中的列分隔符是, 不是預設\t 鍵,需要用 fields TERMINATED BY來指定分隔符

load data infile 'e:\\person.txt' into table person fields TERMINATED BY ',';

source

source 檔案路徑/檔名
  • 其檔案內容必須是合法的sql語句
  • 與load的區別:不用引號,建議使用/分隔路徑,檔案編碼與作業系統編碼一致(gbk)

update 更新

語法:

update 表名 set 列名=新值 where 條件;
update person set sex='男';             // 把所有記錄性別都改為男
update person set sex='男' where id=1;  // 只修改id=1的性別為男

delete 刪除

語法:

delete from 表名; // 刪除表中所有記錄(危險操作)
delete from 表名 where 條件; // 刪除滿足條件的記錄

select 查詢

語法:

select 列名... fromwhere 條件 group by 分組條件 having 分組篩選條件 order by 排序條件 limit;

條件 where

= 等值匹配
!= 不等值匹配
> 大於
< 小於
>= 大於等於
<= 小於等於

邏輯運算子組合多個條件
邏輯與(兩個條件同時成立) and 例如:

select * from hero where sex='女' and loc='建業'; 

邏輯或(兩個條件有一個成立,結果就是真) or

select * from hero where name='小喬' or id=200;
邏輯非 (條件取反) not 

列 between 值1 and 值2 等價於 列 >= 值1 and 列 <= 值2, 注意小值要在前面,包含邊界的值
列 in (值1,值2,… 值n) 等價於 列=值1 or 列=值2 … or 列=值n 注意值列表的長度
like 模糊查詢 其中匹配萬用字元 % 表示匹配0~多個任意字元
萬用字元 _ 表示匹配1個任意字元
例如:

select * from hero where power between 85 and 90;
select * from hero where power >= 85 and power <=90;
not in
not like
not between ... and

排序條件

排序條件:列名 升降序 如果升降序關鍵字省略,預設是asc
升序-> 由小到大 asc
降序-> 由大到小 desc

select * from hero order by power desc limit 10;

多列排序: 排序條件1, 排序條件2 …
先按照條件1排序,條件1中取值相同的,再按照條件2排序

限制返回結果個數

limit m;    // 最多返回m個結果
limit n,m;  // 最多返回m個結果,n代表起始下標,下標從0開始

經常用來實現分頁應用,假設每頁10條

第一頁 limit 0,10;
第二頁 limit 10,10;
第三頁 limit 20,10;

分組條件

select count(*),max(sal),min(sal),sum(sal),avg(sal),deptno from emp group by deptno;
count(*)  表示求每組的個數
max() 求最大值
min() 求最小值
sum() 求和
avg() 求平均值

分組之後,

  • select子句中只能出現分組條件列和組函式,其他列不能出現在select中,
  • order by 子句中只能出現分組條件列和組函式,其他列不能出現在order by中,
    例如:
    select deptno,max(sal),ename from emp group by deptno; // ename不符合剛才的規定
    select deptno,max(sal) from emp order by ename; // 錯誤的

having 也是過濾

但是它的執行順序較後;

where > group by > having > select > order by > limit // sql語句的執行順序
select count(*), deptno from emp where count(*) >=5 group by deptno; 
// 因為where先執行,這時候還沒有分組,不知道個數,錯誤
select count(*), deptno from emp group by deptno having count(*)>=5;
//後執行就可以用count(*)做條件的約束

有時候篩選條件既可以寫在where 上,也可以寫在having (優先採用where)

select count(*), deptno from emp where deptno=10 or deptno=30 group by deptno;
select count(*), deptno from emp group by deptno having deptno=10 or deptno=30;

多列分組 (瞭解)

多個列取值都相同的分為一組

group by1,列2 ...
select count(*),deptno,job from emp group by job,deptno;

多列分組時,列的順序不影響結果

多表結構和連線查詢

select ... from1 inner join2 on 連線條件 
    where  group by  having  order by  limit;
select empno,ename,sal,emp.deptno,dept.deptno,dname,loc from emp 
	inner join dept on emp.deptno = dept.deptno;

表1 表1別名

select empno,ename,sal,e.deptno,d.deptno,dname,loc 
    from emp e inner join dept d on e.deptno = d.deptno;

幾種連線查詢

1 inner join2 on 連線條件  (內連線:兩張表的記錄必須完全滿足連線條件,才會出現在最後結果中)1 left outer join2 on 連線條件  (左外連線)1 right outer join2 on 連線條件  (右外連線)
select empno, ename, e.deptno, d.deptno, d.dname, d.loc 
    from emp e left outer join dept d on d.deptno=e.deptno;

left outer join 位於連線左側的表,不管是否連線到了記錄,都會出現在結果中
符合連線條件的記錄,和內連線效果一樣
不符合連線條件的記錄,對應另一張表的列都是null值

right outer join 位於連線右側的表,不管是否連線到了記錄,都會出現在結果中

outer可以省略

連線查詢的等價寫法

  • 內連線的等價寫法 (重要)
select ... from1,2 where 連線條件;
select e.empno,e.ename,e.deptno,d.deptno,d.dname from emp e, dept d where e.deptno=d.deptno;
  • mysql 獨有的 (瞭解)
select ... from1 inner|left join2 using(deptno); // 兩張表的連線列名要相同
select e.empno,e.ename,e.deptno,d.deptno,d.dname from emp e inner join dept d using(deptno);

常用函式

select count(*) from emp; // 求整張表的行數
select max(sal) from emp; // 求整張表的工資最大值

Bit Functions 位運算函式
Comparison operators 比較運算子
Control flow functions 流程控制
Date and Time Functions 日期函式

    year() 擷取年份
    month()
    date()
    date_add(日期 時間間隔); 其中時間間隔的語法:interval n 單位
    select empno,ename,date_add(hiredate, interval 1 month ),hiredate from emp; 加一個月
    select empno,ename,date_add(hiredate, interval 3 day ),hiredate from emp;3SELECT EXTRACT(DAY_MINUTE FROM '2009-07-02 13:02:03'); 提取日期中的從天到分鐘的部分
    select now() 獲取當前時間

Encryption Functions 加密
Information Functions
Logical operators 邏輯運算子
Miscellaneous Functions 剩餘的函式
Numeric Functions 數學函式

    rand() 生成一個從[0.0 ~ 1.0) 之間的隨機小數, 小於1.0
    floor() 捨去小數
    round() 四捨五入

String Functions 字串函式

    left(字串, n)  n代表從左邊要擷取的字元
    lower()
    upper()
    substr(字串,下標, 長度) 下標從1開始
    求字串長度的例子:select * from hero where char_length(name)=4;

匯出資料

  1. cmd > mysqldump -uroot -p 庫名 >> 要儲存的檔案.sql (source的逆操作, 內部是sql語句)
  2. 把表中的資料儲存到文字檔案中 (load data infile的逆操作)
    select * from 表 into outfile ‘檔案路徑\檔名’