mysql基本操作命令匯總--筆記

一、基本操作

對數據庫以及表的一些基本操作


1-1.關于數據庫

//創建數據庫
create database h_test;        
//查看數據庫
show databases;  
//查看數據庫信息    
show create database h_test;
//修改數據庫的編碼,可使用上一條語句查看是否修改成功
alter database h_test default character set gbk collate gbk_bin;      
//刪除數據庫
drop database h_test;
//綜上,可以直接創建數據庫且設置編碼方式
CREATE DATABASE h_test DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

1-2.關于數據表

//首先選定操作的數據庫
use h_test;
//創建表student
create table student(
  id  int(11),
  name  varchar(20),
  age int(11)
);
//查看數據表
show tables;
//查看數據表信息,后面加上參數/G可使結果更加美觀
show create table student;
//查看表的的字段信息
desc student;
//修改表名
alter table student rename [to] h_student;
//修改字段名
alter table h_student change name stu_name varchar(20);
//修改字段的數據類型
alter table h_student modify id int(20);
//添加字段
alter table h_student add grade float;
//刪除字段
alter table h_student drop grade;
//修改字段的位置
alter table h_student modify stu_name varchar(20) first;
alter table h_student modify id int(11) after age;
//刪除數據表
drop table h_student;

1-3表的約束

約束條件 說明
PRIMARY KEY 主鍵約束,用于唯一標識對應的記錄
FOREIGN KEY 外鍵約束
NOT NULL 非空約束
UNIQUE 唯一性約束
DEFAULT 默認值約束,用于設置字段的默認值

1-4索引

作用:提高表中數據的查詢速度
1.普通索引
2.唯一性索引
3.全文索引
4.單列索引
5.多列索引
6.空間索引

//創建索引
//一.創建表的時候創建索引
create table 表名(
        字段名 數據類型[完整性約束條件],
        ...
        字段名 數據類型,
        [UNIQUE|FULLTEXT|SPATIAL] INDEX|KEY
  );
//1-1.創建普通索引
create table test1(
  id  INT,
  name VARCHAR(20),
  age INT,
  INDEX (id)
);
//可以插入一條數據,查看索引是否被使用
explain select * from test1 where id=1 \G;
//1-2.創建唯一性索引
create table test2(
  id  INT,
  name VARCHAR(20),
  age INT,
  UNIQUE INDEX unique_id(id asc)
);
//1-3.創建全文索引
create table test3(
  id  INT,
  name VARCHAR(20),
  age INT,
  FULLTEXT INDEX fulltext_name(name)
)ENGINE=MyISAM;
//1-4.創建單列索引
create table test4(
  id  INT,
  name VARCHAR(20),
  age INT,
  INDEX single_name(name(20))
);
//1-5.創建多列索引
create table test5(
  id  INT,
  name VARCHAR(20),
  age INT,
  INDEX multi(id,name(20))
);
//1-6.創建空間索引
create table test6(
  id  INT,
  space GEOMETRY NOT NULL,
  SPATIAL INDEX sp(space)
)ENGINE=MyISAM;
---------------------------------------------------
//二.使用create index語句在已經存在的表上創建索引
//首先新建一個表,這個表沒有索引
create table student(
  id int,
  age int,
  name varchar(20),
  intro varchar(40),
  g GEOMETRY NOT NULL
)ENGINE=MyISAM;
//2-1.創建普通索引
create index index_id on student(id);
//2-2.創建唯一性索引
create unique index uniqueidx on student(id);
//2-3.創建單列索引
create index singleidx on student(age);
//2-4.創建多列索引
create index mulitidx on student(name(20),intro(40));
//2-5.創建全文索引
create fulltext index fulltextidx on student(name);
//2-6.創建空間索引
create spatial index spatidx on student(g); 
//下圖是第二種方法創建索引演示后的所有索引
index2
//三.使用alter table語句在已經存在的表上創建索引
//刪除student表,重新創建
drop table student;
create table student(
  id int,
  age int,
  name varchar(20),
  intro varchar(40),
  space GEOMETRY NOT NULL
)ENGINE=MyISAM;
//3-1.創建普通索引
alter table student add index index_id(id);
//3-2.創建唯一性索引
alter table student add unique uniqueidx(id);
//3-3.創建單列索引
alter table student add index singleidx (age);
//3-4.創建多列索引
alter table student add index multidx(name(20),intro(40));
//3-5.創建全文索引
alter table student add fulltext index fulltextidx(name);
//3-6.創建空間索引
alter table student add spatial index spatidx(space);
//下圖演示結果
index3
//刪除索引,有下面兩種方式
//1.使用alter table刪除索引fulltextidx
alter table student drop index fulltextidx;
//2.使用drop index刪除索引spatidx
drop index spatidx on student;
//下圖可看到刪除成功
dropIndex

1-5.添加數據

//重新建立表student
drop table student;
create table student(
  id int,
  name varchar(20) not null,
  grade float
);
//插入一條數據,也可以少某個字段的同時也少對應的數據
insert into student(id,name,grade) values(1,'howie',70);
//也可以不指定字段名,但要注意順序
insert into student values(2,'howie',80);
//也可以這樣添加數據
insert into student set id=3,name="howie",grade=90;
//同時添加多條數據
insert into student values
(4,'howie',80),
(5,'howie',80),
(6,'howie',80);

1-6.更新數據

//更新id=1的數據
update student set name="howie1",grade=60 where id=1;
//批量更新,如果沒有where子句,會更新表中所有對應數據
update student set grade=100 where id<4;

1-7.刪除數據

//刪除id=6的數據
delete from student where id=6;
//批量刪除數據
delete from student where id>3;
//刪除所有數據,DDL(數據定義語言)語句 truncate table student也可以刪除表內所有數據
delete from student;

二 、單表查詢和多表操作

單表查詢:如何從數據庫中獲取你需要的數據
多表查詢:實際開發中,需要進行2張表以上進行操作

2-1-1.單表查詢

//建立表student
create table student(
  id int not null auto_increment,
  name varchar(20) not null,
  grade float,
  primary key(id)
);
//插入數據
insert into student (name,grade) values
("howie1",40),
("howie1",50),
("howie2",50),
("howie3",60),
("howie4",70),
("howie5",80),
("howie6",null);
//查詢全部
select * from student;
//查詢某個字段
select name from student;
//條件查詢,查詢id=2學生的信息
select * from student where id=2;
//in關鍵字查詢,也可以使用not in
select * from student where id IN(1,2,3);
//between and關鍵字查詢
select * from student where id between 2 and 5;
//空值(NULL)查詢,使用IS NULL來判斷
select * from student where grade is null;
//distinct關鍵字查詢
select distinct name from student;
//like關鍵字查詢,查詢以h開頭,e結尾的數據
select * from student where name like "h%e";
//and關鍵字多條件查詢,or關鍵字的使用也是類似
select * from student where id>5 and grade>60;

2-1-2.高級查詢

//聚合函數
//count()函數,sum()函數,avg()函數,max()函數,min()函數
select count(*) from student;
select sum(grade) from student;
select avg(grade) from student;
select max(grade) from student;
select min(grade) from student;
//對查詢結果進行排序
select * from student order by grade;
//分組查詢
//1.單獨使用group by分組
select * from student group by grade;
//2.和聚合函數一起使用
select count(*),grade from student group by grade;
//3.和having關鍵字一起使用
select sum(grade),name from student group by grade having sum(grade) >100;
//使用limit限制查詢結果的數量
select * from student limit 5;
select * from student limit 2,2;
select * from student order by grade desc limit 2,2;
//函數,mysql提供了許多函數
select concat(id,':',name,':',grade) from student;
//為表取別名
select * from student as stu where stu.name="howie";
//為字段取別名,as關鍵字也可以不寫
select name as stu_name,grade stu_grade from student;

2-2.多表操作

1.了解外鍵
2.了解關聯關系
3.了解各種連接查詢多表的數據
4.了解子查詢,會使用各種關鍵字以及比較運算符查詢多表中的數據

2-2-1.外鍵

外鍵是指引用另一個表中的一列或者多列,被引用的列應該具有主鍵約束或者唯一性約束,用于建立和加強兩個數據表之間的連接。

//創建表class,student
create table class(
   id int not null primary key,
   classname varchar(20) not null
)ENGINE=InnoDB;
create table student(
   stu_id int not null primary key,
   stu_name varchar(20) not null,
   cid int not null      -- 表示班級id,它就是class表的外鍵
)ENGINE=InnoDB;
//添加外鍵約束
alter table student add constraint FK_ID foreign key(cid) references class(id);
//刪除外鍵約束
alter table student drop foreign key FK_ID;

看下圖可知外鍵添加成功:

foreign key

2-2-2.操作關聯表

//數據表有三種關聯關系,多對一、多對多、一對一
//學生(student)和班級(class)是多對一關系,添加數據
//首選添加外鍵約束
alter table student add constraint FK_ID foreign key(cid) references class(id);
//添加數據,這兩個表便有了關聯若插入中文在終端顯示空白,可設置set names 'gbk';
insert into class values(1,"軟件一班"),(2,"軟件二班");
insert into student values(1,"howie",1),(2,"howie1",2),(3,"howie2",1),(4,"howie3",2);
//交叉連接
select * from student cross join class;
//內連接,該功能也可以使用where語句實現
select student.stu_name,class.classname from student join class on class.id=student.cid;
//外連接
//首先在student,class表中插入數據
insert into class values(3,"軟件三班");
//左連接,右連接
select s.stu_id,s.stu_name,c.classname from student s left join class c on c.id=s.cid;
select s.stu_id,s.stu_name,c.classname from student s right join class c on c.id=s.cid;
//復合條件連接查詢就是添加過濾條件
//子查詢
//in關鍵字子查詢跟上面的in關鍵字查詢類似
select * from student where cid in(select id from class where id=2);
//exists關鍵字查詢,相當于測試,不產生數據,只返回true或者false,只有返回true,外層才會執行,具體看下圖
select * from student where exists(select id from class where id=12);   -- 外層不會執行
select * from student where exists(select id from class where id=1);    -- 外層會執行
//any關鍵字查詢
 select * from student where cid>any(select id from class);
//all關鍵字查詢
 select * from student where cid=any(select id from class);

具體結果請看下圖:


交叉連接
內連接
left/right join on
exists
any all

三 、事務與存儲過程

事務的概念,會開啟、提交和回滾事務
事務的四種隔離級別
創建存儲過程
調用、查看、修改和刪除存儲過程

3-1 事務管理

start transaction;  -- 開啟事務
commit;             -- 提交事務
rollback;           -- 取消事務(回滾)
//創建表account,插入數據
create table account(
  id int primary key auto_increment,
  name varchar(40),
  money float
);
insert into account(name,money) values('a',1000),('b',2000),('c',3000);
//利用事務實現轉賬功能,首先開啟事務,然后執行語句,提交事務
start transaction;
update account set money=money-100 where name='a';
update account set money=money+100 where name='b';
commit;
//事務的提交,通過這個命令查看mysql提交方式
select @@autocommit; -- 若為1,表示自動提交,為0,就要手動提交
//若事務的提交方式為手動提交
set @@autocommit = 0; -- 設置為手動提交
start transaction;
update account set money=money+100 where name='a';
update account set money=money-100 where name='b';
//現在執行select * from account 可以看到轉賬成功,若此時退出數據庫重新登錄,會看到各賬戶余額沒有改變,所以一定要用commit語句提交事務,否則會失敗
//事務的回滾,別忘記設置為手動提交的模式
start transaction;
update account set money=money-100 where name='a';
update account set money=money+100 where name='b';
//若此時a不想轉賬給b,可以使用事務的回滾
rollback;
//事務的隔離級別
read uncommitted;
read committed;
repeatable read;
serializable;

3-2 存儲過程

//創建查看student表的存儲過程
//創建student表
create table student( 
  id int not null primary key auto_increment, 
  name varchar(4), 
  grade float 
)ENGINE=InnoDB default character set utf8;
delimiter //  -- 將mysql的結束符設置為//
create procedure Proc()
  begin
  select * from student;
  end //
delimiter ;   -- 將mysql的結束符設置為;
call Proc();  -- 這樣就可以調用該存儲過程
//變量的使用,mysql中變量不用事前申明,在用的時候直接用“@變量名”使用就可以
set @number=100; -- 或set @num:=1;
//定義條件和處理程序
//光標的使用
//1.聲明光標
DECLARE * cursor_name* CURSOR FOR select_statement
2. 光標OPEN語句
OPEN cursor_name
3. 光標FETCH語句
FETCH cursor_name INTO var_name [, var_name] ...
4. 光標CLOSE語句
CLOSE cursor_name
//流程控制的使用  不做介紹

3-3 調用存儲過程

//定義存儲過程
delimiter //
create procedure proc1(in name varchar(4),out num int)
begin
select count(*) into num from student where name=name;
end//
delimiter ;
//調用存儲過程
call proc1("tom",@num) -- 查找名為tom學生人數
//查看結果
select @num;  -- 看下圖
call proc1
//查看存儲過程
 show procedure status like 'p%' \G -- 獲得以p開頭的存儲過程信息
//修改存儲過程
alter {procedure|function} sp_name[characteristic...]
//刪除存儲過程
drop procedure proc1;

四、視圖

如何創建視圖
查看、修改、更新、刪除視圖

4-1、視圖的基本操作

//在單表上創建視圖,重新創建student表,插入數據
create table student(
  id int not null primary key auto_increment,
  name varchar(10) not null,
  math float,
  chinese float
);
insert into student(name,math,chinese) values
('howie1',66,77),
('howie2',66,77),
('howie3',66,77);
//開始創建視圖
create view stu_view as select math,chinese,math+chinese from student;  -- 下圖可看出創建成功
//也可以創建自定義字段名稱的視圖
create view stu_view2(math,chin,sum) as select math,chinese,math+chinese from student;
stu_view

stu_view2
//在多表上創建視圖,創建表stu_info,插入數據
create table stu_info(
  id int not null primary key auto_increment,
  class varchar(10) not null,
  addr varchar(100)
);
insert into stu_info(class,addr) values
('1','anhui'),
('2','fujian'),
('3','guangdong');
//創建視圖stu_class
create view stu_class(id,name,class) as 
select student.id,student.name,stu_info.class from 
student,stu_info where student.id=stu_info.id;
//查看視圖
desc stu_class;
show table status like 'stu_class'\G
show create view stu_class\G
//修改視圖
create or replace view stu_view as select * from student;
alter view stu_view as select chinese from student;
//更新視圖
update stu_view set chinese=100;
insert into student values(null,'haha',100,100);
delete from stu_view2 where math=100;
//刪除視圖
drop view if exists stu_view2;
stu_class

五、總結

筆記參考《MySql數據庫入門》
基本命令就這么多,仍需多多敲寫鞏固
以上命令本人全部敲過,若有錯誤,敬請指出,希望有幫助,謝謝。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,363評論 6 532
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,497評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,305評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,962評論 1 311
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,727評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,193評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,257評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,411評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,945評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,777評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,978評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,519評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,216評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,642評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,878評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,657評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,960評論 2 373

推薦閱讀更多精彩內容