mysql的簡單基本操作


安裝
sudo apt-get install mysql-server mysql-client
獲取默認安裝的密碼
sudo grep mysql_root_passwd /root/env.txt
啟動服務
service mysql start
停止服務
service mysql stop
重啟服務
service mysql restart
允許數(shù)據(jù)庫遠程連接
1.找到mysql配置文件并修改
 sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf
 將bind-address=127.0.0.1注釋
2.登錄mysql技竟,運行命令
grant all privileges on *.* to 'root'@'%' identified by 'mysql' with grant option;
flush privileges;
3.重啟mysql

在mysql中包含的數(shù)據(jù)類型很多,這里主要列出來常用的幾種
  • 數(shù)字:int,decimal
  • 字符串:varchar,text
  • 日期:datetime
  • 布爾:bit
約束
  • 主鍵 primary key
  • 非空 not null
  • 惟一 unique
  • 默認 default
  • 外鍵 foreign key

使用命令連接數(shù)據(jù)庫
mysql -uroot -p

查看版本:select version();


創(chuàng)建數(shù)據(jù)庫
mysql> create database 數(shù)據(jù)庫名 charset=utf8;
刪除數(shù)據(jù)庫
mysql> drop database 數(shù)據(jù)庫名;
切換數(shù)據(jù)庫
mysql> use 數(shù)據(jù)庫名;
查看當前選擇的數(shù)據(jù)庫
mysql> show databases;

表操作

顯示當前數(shù)據(jù)庫中的所有表
mysql> show tables;
創(chuàng)建表

auto_increment表示自動增長

create table 表名(列及類型);如:
mysql> create table students( id int auto_increment primary key not null, name varchar(10) not null, gender bit default 1, birthday datetime);
查看表結構
desc 表名; 例如:
mysql> desc students;
修改表
alter table 表名 add|change|drop 列名 類型;
如:
mysql> alter table students add isDelete bit default 0;
刪除表
drop table 表名;
更改表名稱
rename table 原表名 to 新表名;
查看表的創(chuàng)建語句
show create table 表名;
例如:mysql> show create table students;

數(shù)據(jù)操作

查詢
select * from 表名
增加
全列插入:insert into 表名 values(...)
例如: mysql> insert into students values(0,'張三',1,'1990-7-7',0);

缺省插入:insert into 表名(列1,...) values(值1,...)
例如:mysql> insert into students(name) values('李四');
      mysql> insert into students(gender,name) values(0,'小龍女');

同時插入多條數(shù)據(jù):insert into 表名 values(...),(...)...;
例如:mysql> insert into students(name) values('王五'),('董永');
  或insert into 表名(列1,...) values(值1,...),(值1,...)...;
  • 主鍵列是自動增長,但是在全列插入時需要占位,通常使用0,插入成功后以實際數(shù)據(jù)為準
修改
update 表名 set 列1=值1,... where 條件
例如:mysql> update students set birthday='1990-2-2' where id=2;
      mysql> update students set gender=0,birthday='2017-9-21' where id=4;
刪除
delete from 表名 where 條件
例如:mysql> delete from students where id=5;

truncate table 表名  (這種方式刪除數(shù)據(jù)后 重新插入的數(shù)據(jù)id從1開始)
邏輯刪除,本質(zhì)就是修改操作update
如果需要刪除則
update students isdelete=1 where ...;
例如 : mysql> update students set isDelete= 1 where id=4;
  mysql> select * from students where isDelete=0;   通過添加條件查找沒有刪除項

備份與恢復

數(shù)據(jù)備份
進入超級管理員
sudo -s
進入mysql庫目錄
cd /var/lib/mysql
運行mysqldump命令
mysqldump –uroot –p 數(shù)據(jù)庫名 > ~/Desktop/備份文件.sql;
按提示輸入mysql的密碼
例如: root@ubuntu:/var/lib/mysql# mysqldump -uroot -p python3 > ~/Desktop/bak.sql
數(shù)據(jù)恢復
連接mysqk,創(chuàng)建數(shù)據(jù)庫
退出連接值朋,執(zhí)行如下命令
mysql -uroot –p 數(shù)據(jù)庫名 < ~/Desktop/備份文件.sql
根據(jù)提示輸入mysql密碼
例如:lin@ubuntu:~/Desktop$ mysql -uroot -p py31 < bak.sql

高級查詢

基本查詢
select * from 表名
例如:mysql> select * from students;
或者查詢部分:
mysql> select id,name from students;
+----+-----------+
| id | name      |
+----+-----------+
|  1 | 張三      |
|  2 | 小龍女    |
|  3 | 王五      |
|  4 | 董永      |
|  5 | 張三      |
+----+-----------+
5 rows in set (0.01 sec)
去除重復行 (distinct 比較的是相同行)
mysql> select distinct name from students;
+-----------+
| name      |
+-----------+
| 張三      |
| 小龍女    |
| 王五      |
| 董永      |
+-----------+
4 rows in set (0.00 sec)

mysql> select distinct id,name from students;
+----+-----------+
| id | name      |
+----+-----------+
|  1 | 張三      |
|  2 | 小龍女    |
|  3 | 王五      |
|  4 | 董永      |
|  5 | 張三      |
+----+-----------+
5 rows in set (0.00 sec)
條件
select * from 表名 where 條件; (條件結果為true的行才會出現(xiàn)在結果集中)
比較運算符
  • 等于=
  • 大于>
  • 大于等于>=
  • 小于<
  • 小于等于<=
  • 不等于!=或<>
  • 查詢編號大于3的學生
mysql> select id,name from students where id<3;
+----+-----------+
| id | name      |
+----+-----------+
|  1 | 張三      |
|  2 | 小龍女    |
+----+-----------+
2 rows in set (0.02 sec)
邏輯運算符
  • and
  • or
  • not
mysql> select id,name from students where id<3 and gender=0;
+----+-----------+
| id | name      |
+----+-----------+
|  2 | 小龍女    |
+----+-----------+
1 row in set (0.00 sec)
模糊查詢
  • like
  • %表示任意多個任意字符
  • _表示一個任意字符
mysql> select id,name from students;
+----+-----------+
| id | name      |
+----+-----------+
|  1 | 張三      |
|  2 | 小龍女    |
|  3 | 王五      |
|  4 | 董永      |
|  6 | 張世界    |
|  7 | 張五      |
+----+-----------+
6 rows in set (0.00 sec)

mysql> select id,name from students where name like '張%';
+----+-----------+
| id | name      |
+----+-----------+
|  1 | 張三      |
|  6 | 張世界    |
|  7 | 張五      |
+----+-----------+
3 rows in set (0.00 sec)

mysql> select id,name from students where name like '張_';
+----+--------+
| id | name   |
+----+--------+
|  1 | 張三   |
|  7 | 張五   |
+----+--------+
2 rows in set (0.00 sec)
范圍查詢
  • in表示在一個非連續(xù)的范圍內(nèi)
mysql> select id,name from students where id in(1,3,6);
+----+-----------+
| id | name      |
+----+-----------+
|  1 | 張三      |
|  3 | 王五      |
|  6 | 張世界    |
+----+-----------+
3 rows in set (0.00 sec)
  • between ... and ...表示在一個連續(xù)的范圍內(nèi)
mysql> select id,name from students where id between 2 and 4;
+----+-----------+
| id | name      |
+----+-----------+
|  2 | 小龍女    |
|  3 | 王五      |
|  4 | 董永      |
+----+-----------+
3 rows in set (0.00 sec)
空判斷
  • 注意:null與''是不同的
  • 判空 is null
mysql> select id,name,birthday from students where birthday is null;
+----+-----------+----------+
| id | name      | birthday |
+----+-----------+----------+
|  2 | 小龍女    | NULL     |
|  3 | 王五      | NULL     |
|  4 | 董永      | NULL     |
+----+-----------+----------+
3 rows in set (0.00 sec)

mysql> select id,name,birthday from students where birthday is not null;
+----+-----------+---------------------+
| id | name      | birthday            |
+----+-----------+---------------------+
|  1 | 張三      | 1990-01-01 00:00:00 |
|  6 | 張世界    | 1990-01-02 00:00:00 |
|  7 | 張五      | 1990-01-02 00:00:00 |
+----+-----------+---------------------+
3 rows in set (0.00 sec)
優(yōu)先級
  • 小括號,not巩搏,比較運算符昨登,邏輯運算符
  • and比or先運算,如果同時出現(xiàn)并希望先算or塔猾,需要結合()使用

聚合

為了快速得到統(tǒng)計數(shù)據(jù)篙骡,提供了5個聚合函數(shù)

count(*)表示計算總行數(shù),括號中寫星與列名丈甸,結果是相同的
mysql> select count(*) from students;
+----------+
| count(*) |
+----------+
|        6 |
+----------+
1 row in set (0.01 sec)
max(列)表示求此列的最大值
mysql> select max(id) from students where gender=0;
+---------+
| max(id) |
+---------+
|       7 |
+---------+
1 row in set (0.00 sec)
min(列)表示求此列的最小值
mysql> select min(id) from students where gender=0;
+---------+
| min(id) |
+---------+
|       2 |
+---------+
1 row in set (0.00 sec)
sum(列)表示求此列的和
mysql> select sum(id) from students where gender=1;
+---------+
| sum(id) |
+---------+
|       8 |
+---------+
1 row in set (0.00 sec)
avg(列)表示求此列的平均值
mysql> select avg(id) from students where gender=0;
+---------+
| avg(id) |
+---------+
|  5.0000 |
+---------+
1 row in set (0.00 sec)

分組

按照字段分組糯俗,表示此字段相同的數(shù)據(jù)會被放到一個組中
分組后,只能查詢出相同的數(shù)據(jù)列睦擂,對于有差異的數(shù)據(jù)列無法出現(xiàn)在結果集中
可以對分組后的數(shù)據(jù)進行統(tǒng)計得湘,做聚合運算

select 列1,列2,聚合... from 表名 group by 列1,列2,列3...

mysql> select * from students;
+----+-----------+--------+---------------------+----------+
| id | name      | gender | birthday            | isDelete |
+----+-----------+--------+---------------------+----------+
|  1 | 張三      | 1      | 1990-07-07 00:00:00 |          |
|  2 | 李四      | 1      | 1990-02-02 00:00:00 |          |
|  3 | 小龍女    |        | NULL                |          |
|  4 | 王五      |        | 2017-09-21 00:00:00 | 1        |
+----+-----------+--------+---------------------+----------+
4 rows in set (0.00 sec)

mysql> select gender as  gender,count(*) from students group by gender;
+--------+----------+
| gender | count(*) |
+--------+----------+
|        |        2 |
| 1      |        2 |
+--------+----------+
2 rows in set (0.04 sec)
分組后的數(shù)據(jù)篩選
select 列1,列2,聚合... from 表名
group by 列1,列2,列3...
having 列1,...聚合...

mysql> select gender,count(*) from students group by gender having gender=1;
+--------+----------+
| gender | count(*) |
+--------+----------+
| 1      |        2 |
+--------+----------+
1 row in set (0.00 sec)
對比where與having

where是對from后面指定的表進行數(shù)據(jù)篩選,屬于對原始數(shù)據(jù)的篩選
having是對group by的結果進行篩選

排序
select * from 表名
order by 列1 asc|desc,列2 asc|desc,...

將行數(shù)據(jù)按照列1進行排序顿仇,如果某些行列1的值相同時淘正,則按照列2排序摆马,以此類推
默認按照列值從小到大排列
asc從小到大排列,即升序
desc從大到小排序鸿吆,即降序

按id升序
mysql> select id,name from students order by id;
+----+-----------+
| id | name      |
+----+-----------+
|  1 | 張三      |
|  2 | 李四      |
|  3 | 小龍女    |
|  4 | 王五      |
+----+-----------+
4 rows in set (0.00 sec)

按男生學號降序
mysql> select id,name from students where gender = 1 order by id desc;  
+----+--------+
| id | name   |
+----+--------+
|  2 | 李四   |
|  1 | 張三   |
+----+--------+
2 rows in set (0.00 sec)
獲取部分行 (分頁)
select * from 表名 limit start,count
從start開始囤采,獲取count條數(shù)據(jù)
start索引從0開始

mysql> select id,name from students limit 2,1;
+----+-----------+
| id | name      |
+----+-----------+
|  3 | 小龍女    |
+----+-----------+
1 row in set (0.00 sec)

分頁
select * from students
where isdelete=0
limit (n-1)*m,m

完整的sql語句

select distinct *
from 表名
where ....
group by ... having ...
order by ...
limit star,count

執(zhí)行順序為:
from 表名
where ....
group by ...
select distinct *
having ...
order by ...
limit star,count

數(shù)據(jù)庫高級部分

關系
外鍵
創(chuàng)建成績表
mysql> create table scores(
    -> id int primary key auto_increment not null,
    -> score decimal(4,1),
    -> stuid int,
    -> subid int,
    -> foreign key(stuid) references students(id),
    -> foreign key(subid) references subjects(id));

級聯(lián)操作的類型包括:

  • restrict(限制):默認值,拋異常
  • cascade(級聯(lián)):如果主表的記錄刪掉惩淳,則從表中相關聯(lián)的記錄都將被刪除
  • set null:將外鍵設置為空
  • no action:什么都不做
連接

連接查詢分類如下:

  • 表A inner join 表B:表A與表B匹配的行會出現(xiàn)在結果中
  • 表A left join 表B:表A與表B匹配的行會出現(xiàn)在結果中蕉毯,外加表A中獨有的數(shù)據(jù),未對應的數(shù)據(jù)使用null填充
  • 表A right join 表B:表A與表B匹配的行會出現(xiàn)在結果中思犁,外加表B中獨有的數(shù)據(jù)代虾,未對應的數(shù)據(jù)使用null填充
    在查詢或條件中推薦使用“表名.列名”的語法
    如果多個表中列名不重復可以省略“表名.”部分
    如果表的名稱太長,可以在表名后面使用' as 簡寫名'或' 簡寫名'激蹲,為表起個臨時的簡寫名稱
mysql> select students.name, subjects.title,scores.score 
from scores 
inner join students on scores.stuid=students.id 
inner join subjects on scores.subid=subjects.id;

+-----------+--------+-------+
| name      | title  | score |
+-----------+--------+-------+
| 張三      | python | 100.0 |
| 李四      | python |  99.0 |
| 小龍女    | python |  71.0 |
| 張三      | linux  |  90.0 |
| 李四      | linux  |  79.0 |
| 小龍女    | linux  |  89.0 |
| 張三      | java   |  93.0 |
| 李四      | java   |  91.0 |
| 小龍女    | java   |  95.0 |
+-----------+--------+-------+
9 rows in set (0.01 sec)

mysql> select students.name,subjects.title,scores.score from students 
    -> inner join scores on students.id=scores.stuid
    -> inner join subjects on scores.subid=students.id;
+-----------+--------+-------+
| name      | title  | score |
+-----------+--------+-------+
| 張三      | python | 100.0 |
| 張三      | linux  | 100.0 |
| 張三      | java   | 100.0 |
| 張三      | redis  | 100.0 |
| 李四      | python |  79.0 |
| 李四      | linux  |  79.0 |
| 李四      | java   |  79.0 |
| 李四      | redis  |  79.0 |
| 小龍女    | python |  95.0 |
| 小龍女    | linux  |  95.0 |
| 小龍女    | java   |  95.0 |
| 小龍女    | redis  |  95.0 |
+-----------+--------+-------+
12 rows in set (0.00 sec)
自引用
mysql> create table areas(id int primary key auto_increment not null,
    -> title varchar(20),pid int,
    -> foreign key(pid) references areas(id));
視圖
mysql> create view v_1 as 
    -> select stu.*,sco.score,sub.title from scores as sco
    -> inner join students as stu on sco.stuid=stu.id 
    -> inner join subjects as sub on sco.subid=sub.id;

視圖的用途就是查詢

mysql> select * from v_1;
+----+-----------+--------+---------------------+-------+--------+
| id | name      | gender | birthday            | score | title  |
+----+-----------+--------+---------------------+-------+--------+
|  1 | 張三      | 1      | 1990-01-01 00:00:00 | 100.0 | python |
|  2 | 小龍女    |        | NULL                |  90.0 | python |
|  3 | 王五      | 1      | NULL                |  85.0 | python |
|  1 | 張三      | 1      | 1990-01-01 00:00:00 |  99.0 | kotlin |
|  2 | 小龍女    |        | NULL                |  93.0 | kotlin |
|  3 | 王五      | 1      | NULL                |  81.0 | kotlin |
|  1 | 張三      | 1      | 1990-01-01 00:00:00 |  71.0 | php    |
|  2 | 小龍女    |        | NULL                |  95.0 | php    |
|  3 | 王五      | 1      | NULL                |  79.0 | php    |
+----+-----------+--------+---------------------+-------+--------+
事務
  • 當一個業(yè)務邏輯需要多個sql完成時棉磨,如果其中某條sql語句出錯,則希望整個操作都退回
  • 使用事務可以完成退回的功能学辱,保證業(yè)務邏輯的正確性
    事務四大特性(簡稱ACID)
    • 2.1 原子性(Atomicity):事務中的全部操作在數(shù)據(jù)庫中是不可分割的乘瓤,要么全部完成,要么均不執(zhí)行
    • 2-2 一致性(Consistency):幾個并行執(zhí)行的事務策泣,其執(zhí)行結果必須與按某一順序串行執(zhí)行的結果相一致
    • 2-3 隔離性(Isolation):事務的執(zhí)行不受其他事務的干擾馅扣,事務執(zhí)行的中間結果對其他事務必須是透明的
    • 2-4 持久性(Durability):對于任意已提交事務,系統(tǒng)必須保證該事務對數(shù)據(jù)庫的改變不被丟失着降,即使數(shù)據(jù)庫出現(xiàn)故障
  • 要求:表的類型必須是innodb或bdb類型,才可以對此表使用事務
事務語句
開啟begin;
提交commit;
回滾rollback;

索引

create index 索引名 on 表名(列名(length))
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末拗军,一起剝皮案震驚了整個濱河市任洞,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌发侵,老刑警劉巖交掏,帶你破解...
    沈念sama閱讀 222,104評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異刃鳄,居然都是意外死亡盅弛,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,816評論 3 399
  • 文/潘曉璐 我一進店門叔锐,熙熙樓的掌柜王于貴愁眉苦臉地迎上來挪鹏,“玉大人,你說我怎么就攤上這事愉烙√趾校” “怎么了?”我有些...
    開封第一講書人閱讀 168,697評論 0 360
  • 文/不壞的土叔 我叫張陵步责,是天一觀的道長返顺。 經(jīng)常有香客問我禀苦,道長,這世上最難降的妖魔是什么遂鹊? 我笑而不...
    開封第一講書人閱讀 59,836評論 1 298
  • 正文 為了忘掉前任振乏,我火速辦了婚禮,結果婚禮上秉扑,老公的妹妹穿的比我還像新娘慧邮。我一直安慰自己,他們只是感情好邻储,可當我...
    茶點故事閱讀 68,851評論 6 397
  • 文/花漫 我一把揭開白布赋咽。 她就那樣靜靜地躺著,像睡著了一般吨娜。 火紅的嫁衣襯著肌膚如雪脓匿。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,441評論 1 310
  • 那天宦赠,我揣著相機與錄音陪毡,去河邊找鬼。 笑死勾扭,一個胖子當著我的面吹牛毡琉,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播妙色,決...
    沈念sama閱讀 40,992評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼桅滋,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了身辨?” 一聲冷哼從身側響起丐谋,我...
    開封第一講書人閱讀 39,899評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎煌珊,沒想到半個月后号俐,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,457評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡定庵,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,529評論 3 341
  • 正文 我和宋清朗相戀三年吏饿,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蔬浙。...
    茶點故事閱讀 40,664評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡猪落,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出敛滋,到底是詐尸還是另有隱情许布,我是刑警寧澤,帶...
    沈念sama閱讀 36,346評論 5 350
  • 正文 年R本政府宣布绎晃,位于F島的核電站蜜唾,受9級特大地震影響杂曲,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜袁余,卻給世界環(huán)境...
    茶點故事閱讀 42,025評論 3 334
  • 文/蒙蒙 一擎勘、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧颖榜,春花似錦棚饵、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,511評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至且蓬,卻和暖如春欣硼,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背恶阴。 一陣腳步聲響...
    開封第一講書人閱讀 33,611評論 1 272
  • 我被黑心中介騙來泰國打工诈胜, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人冯事。 一個月前我還...
    沈念sama閱讀 49,081評論 3 377
  • 正文 我出身青樓焦匈,卻偏偏與公主長得像,于是被迫代替她去往敵國和親昵仅。 傳聞我的和親對象是個殘疾皇子缓熟,可洞房花燭夜當晚...
    茶點故事閱讀 45,675評論 2 359

推薦閱讀更多精彩內(nèi)容