1. 程式人生 > 實用技巧 >基本資料庫操作

基本資料庫操作

關係型資料庫:sqllite,db2,oracle,access,sql server,MySQL
非關係型資料庫:MongoDB,redis

學員管理:
表結構:班級\學生\老師

	班級表(第一天):
		id    title
		 1    全棧4期
		 2    全棧5期

		學生表:
​			 id     name      班級ID(FK)
​			  1     張英傑      1
​			 
​		老師表(第一天):
​			id        name
​			 1       林海峰
​			 2       林狗
​			 3       苑日天


​		 
​		老師班級關係表:
​			id     老師ID    班級ID
​			 1       1          1
​			 2       1          2
​			 3       2          2
	
單表操作:
	- 增
	- 刪
	- 改
	- 查
一對多操作:
	- 增
	- 刪
	- 改
	- 查
多對多操作:
	- 增
	- 刪
	- 改
	- 查

1. 關於連線

資料夾【資料庫】 databases
檔案【表】 tables
資料行【行】
資料行
資料行

	連線:
	預設:使用者root
	
	show databases;
	
	use 資料庫名稱;
	
	show tables;
	
	select * from 表名;
	
	select name,age,id from 表名;
	
	mysql資料庫user表
	use mysql;
	select user,host from user;


	建立使用者:
		  create user 'alex'@'192.168.1.1' identified by '123123';
		  create user 'alex'@'192.168.1.%' identified by '123123';
		  create user 'alex'@'%' identified by '123123';
	授權:
		  許可權  人
		  
		  grant select,insert,update  on db1.t1 to 'alex'@'%';
		  grant all privileges  on db1.t1 to 'alex'@'%';
		  
		  revoke all privileges on db1.t1 from 'alex'@'%';
		  
	DBA: 使用者名稱密碼

2. SQL語句

資料庫轉儲dump
	備份:資料表結構+資料
	mysqldump -uroot db1 > db.sql -p
	備份:資料表結構
	mysqldump -uroot -d db1 > db.sql -p
	
	執行檔案:
	create database db5;
	mysqldump -uroot -d db5 < db1.sql -p;
	

操作資料夾
		create database db2;
		create database db2 default charset utf8; *****
		show databases;
		drop database db2;
操作檔案
		show tables;
		create table t1(id int,name char(10)) default charset=utf8;
		create table t1(id int,name char(10))engine=innodb default charset=utf8;
		create table t3(id int auto_increment,name char(10))engine=innodb default charset=utf8;  *****
		 
		create table t1(
			列名 型別 null,
			列名 型別 not null,
			列名 型別 not null auto_increment primary key,
			id int,
			name char(10)
		)engine=innodb default charset=utf8;
			# innodb 支援事務,原子性操作,可回滾
			# myisam myisam 不支援回滾
			
			auto_increment 表示:自增
			primary key:  表示 約束(不能重複且不能為空); 加速查詢
			not null: 是否為空

3. 資料型別

數字:
tinyint
int
bigint

FLOAT
	0.00000100000123000123001230123
DOUBLE
    0.00000000000000000000100000123000123001230123
    0.00000100000123000000000000000
decimal
	0.1

字串:
char(10)      速度快()
    root      
    root     
varchar(10)   節省空間
	root
PS: 建立資料表定長列往前放

text

上傳檔案: 
    檔案存硬碟
    db存路徑
時間型別
DATETIME

enum
set

4. 外來鍵

  • 建立多約束外來鍵時,最後一行不要加逗號

    好處:
    1.節省空間
    2.新增約束

create table userinfo(
			uid bigint auto_increment primary key,
			name varchar(32),
			department_id int,
			xx_id int,
			constraint fk_user_depar foreign key (department_id) references department(id)
		)engine=innodb default charset=utf8;
		
create table department(
            id bigint auto_increment primary key,
            title char(15)
        )engine=innodb default charset=utf8;

5. 作業

一個漢字在utf8中佔3個位元組

create table class(
	cid int auto_increment primary key,
    caption varchar(32)
)engine=innodb default charset=utf8;
create table student(
    sid int auto_increment primary key,
    sname varchar(32),
    gender char(5),
    class_id int,
    constraint fk_stu_class foreign key (class_id) references class(cid)
)engine=innodb default charset=utf8;
create table teacher(
tid int auto_increment primary key,
    tname varchar(35)
)engine=innodb default charset=utf8;
create table course(
cid int auto_increment primary key,
    cname varchar(32),
    teacher_id int,
    constraint fk_cou_tea foreign key (teacher_id) references teacher(tid)
)engine=innodb default charset=utf8;
create table score(
sid int auto_increment primary key,
    student_id int,
    corse_id int,
    number int,
    constraint fk_sco_stu foreign key (student_id) references student(sid),
    constraint fk_sco_cor foreign key (corse_id) references course(cid)
)engine=innodb default charset=utf8;

6. 主鍵

主鍵:
    一個表只能有一個主鍵
    主鍵可以由多列組成(保證唯一即可)
    primary key (nid, pid),
    
    CREATE TABLE t5 (
        nid int(11) NOT NULL AUTO_INCREMENT,
        pid int(11) not NULL,
        num int(11),
        primary key(nid,pid)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
        
    # t5有聯合主鍵,則外來鍵可以複合,如下
	create table t6(
        id int auto_increment primary key,
        name char(10),
        id1 int,
        id2 int,
        CONSTRAINT fk_t5_t6 foreign key (id1,id2) REFERENCES t5(nid,pid)
        )engine=innodb default charset=utf8;
- 資料行(增刪改查)

    insert into tb1(name,age) values('alex',18);
	
	drop table tb1;
    delete from tb1;
    truncate table tb1;
    delete from tb1 where id > 10

    update tb1 set name='root' where id > 10

    select * from tb;
    select id,name from tb;

7. 自增

desc t10;  # 檢視table結構屬性

show create table t10;

show create table t10 \G; # 反轉

alter table t10 AUTO_INCREMENT=20;  # 在刪除某行之後,自增值仍為原數,需要重新調整自增數
MySQL: 自增步長
    基於會話級別:(每次登入的會話)
        show session variables like 'auto_inc%';	檢視全域性變數
        set session auto_increment_increment=2; 	設定會話步長
        # set session auto_increment_offset=10;		設定起始值
    基於全域性級別:
        show global variables like 'auto_inc%';	    檢視全域性變數
        set global auto_increment_increment=2; 	    設定會話步長
        # set global auto_increment_offset=10;
		SqlServer:自增步長:(可直接在單獨table中設定步長與起始值)
			基礎表級別:
				CREATE TABLE `t5` (
				  `nid` int(11) NOT NULL AUTO_INCREMENT,
				  `pid` int(11) NOT NULL,
				  `num` int(11) DEFAULT NULL,
				  PRIMARY KEY (`nid`,`pid`)
				) ENGINE=InnoDB AUTO_INCREMENT=4, 步長=2 DEFAULT CHARSET=utf8
				
				CREATE TABLE `t6` (
				  `nid` int(11) NOT NULL AUTO_INCREMENT,
				  `pid` int(11) NOT NULL,
				  `num` int(11) DEFAULT NULL,
				  PRIMARY KEY (`nid`,`pid`)
				) ENGINE=InnoDB AUTO_INCREMENT=4, 步長=20 DEFAULT CHARSET=utf8

8. 唯一索引

create table t1(
    id int ....,
    num int,
    xx int,
    unique 唯一索引名稱 (列名,列名),  # 組合需唯一,聯合唯一索引
    constraint ....
)
		# 
		1   1   1
		2   1   2
	
	PS: 
        唯一:
        	約束不能重複(**可以為空**)
        	PS: 主鍵不能重複(**不能為空**)
        加速查詢

9. 外來鍵的變種

9.1 一對多

		a. 使用者表和部門表
		
			使用者:
				1 alex     1
				2 root	   1
				3 egon	   2
				4 laoyao   3
				
			部門:
				1 服務
				2 保安
				3 公關
				
			===》 一對多

9.2 一對一

		b. 使用者表和部落格表
			使用者表:
				1 alex    
				2 root	   
				3 egon	   
				4 laoyao   
			部落格表:(單人只能單一部落格)
								  FK() + 唯一 (unique:單列不能重複)
				1   /yuanchenqi/   4
				2    /alex3714/    1
				3    /asdfasdf/    3
				4    /ffffffff/    2
				
			===> 一對一
  • 某些人能操作資料表

  • 上述浪費password空間,調整為info與admin表

				create table userinfo1(
					id int auto_increment primary key,
					name char(10),
					gender char(10),
					email varchar(64)
				)engine=innodb default charset=utf8;

				create table admin(
					id int not null auto_increment primary key,
					username varchar(64) not null,
					password VARCHAR(64) not null,
					user_id int not null,
					unique uq_u1 (user_id),
					CONSTRAINT fk_admin_u1 FOREIGN key (user_id) REFERENCES userinfo1(id)
				)engine=innodb default charset=utf8;

9.2 多對多

示例1:
使用者表
相親表

示例2:unique 聯合索引
使用者表
主機表
使用者主機關係表
===》多對多 (雙向外來鍵一對多

				create table userinfo2(
					id int auto_increment primary key,
					name char(10),
					gender char(10),
					email varchar(64)
				)engine=innodb default charset=utf8;

				create table host(
					id int auto_increment primary key,
					hostname char(64)
				)engine=innodb default charset=utf8;


				create table user2host(
					id int auto_increment primary key,
					userid int not null,
					hostid int not null,
					unique uq_user_host (userid,hostid),
					CONSTRAINT fk_u2h_user FOREIGN key (userid) REFERENCES userinfo2(id),
					CONSTRAINT fk_u2h_host FOREIGN key (hostid) REFERENCES host(id)
				)engine=innodb default charset=utf8;

10. 資料行操作補充

		增
			insert into tb11(name,age) values('alex',12);
			insert into tb11(name,age) values('alex',12),('root',18);
			insert into tb12(name,age) select name,age from tb11;
		刪
			delete from tb12;
			delete from tb12 where id !=2 
			delete from tb12 where id =2 
			delete from tb12 where id > 2 
			delete from tb12 where id >=2 
			delete from tb12 where id >=2 or name='alex'
			delete from tb12 where id >=2 and name='alex'
			
		    drop table tb1;
            delete from tb1;
            truncate table tb1;
		改
			update tb12 set name='alex' where id>12 and name='xx'
			update tb12 set name='alex',age=19 where id>12 and name='xx'
		查
			select * from tb12;
			
			select id,name from tb12;
			
			select id,name from tb12 where id > 10 or name ='xxx';
			
			select id,name as cname from tb12 where id > 10 or name ='xxx'; # as cname別名
			
			select name,age,11(11為額外新增的列) from tb12;
			
			
			其他:
				select * from tb12 where id != 1 (<>也為不等於)
				select * from tb12 where id in (1,5,12);
				select * from tb12 where id not in (1,5,12);
				select * from tb12 where id in (select id from tb11)
				select * from tb12 where id between 5 and 12;
			
			
			萬用字元:
				select * from tb12 where name like "a%" #以a開頭的字串
				select * from tb12 where name like "a_" #以a開頭的後一位佔位
			
			
			分頁:(便於檢視,且降低服務端或客戶端壓力)
                    select * from tb12 limit 10;

                    select * from tb12 limit 0,10;
                    select * from tb12 limit 10,10; # 起始位置,之後的多少條
                    select * from tb12 limit 20,10;

                    select * from tb12 limit 10 offset 20;  # offset為起點
             		
             		python實現分頁:
                        # page = input('請輸入要檢視的頁碼')
                        # page = int(page)
                        # (page-1) * 10
                        # select * from tb12 limit 0,10; 1 
                        # select * from tb12 limit 10,10;2
               
               
               排序:
					select * from tb12 order by id desc; 大到小
					select * from tb12 order by id asc;  小到大
					select * from tb12 order by age desc,id desc;  先按照age降序,如果中間列重複,則再按照id降序排
					 
					取後10條資料
					select * from tb12 order by id desc limit 10;
			    
			    
			    分組:
					select count(id),max(id),part_id from userinfo5 group by part_id;
					
					聚合函式
					count
					max
					min
					sum
					avg
					
					**** 如果對於聚合函式結果進行二次篩選時?必須使用having ****
					select count(id),part_id from userinfo5 group by part_id having count(id) > 1;
					
					where後不能加聚合函式
					select count(id),part_id from userinfo5 where id > 0 group by part_id having count(id) > 1;
			   
			   
			   	連表操作:
				
					select * from userinfo5,department5(笛卡爾積) 需宣告關係,如下:
					select * from userinfo5,department5 where userinfo5.part_id = department5.id
					
					select * from userinfo5 left join department5 on userinfo5.part_id = department5.id
					select * from department5 left join userinfo5 on userinfo5.part_id = department5.id
					# userinfo5左邊全部顯示
					
					# select * from userinfo5 right join department5 on userinfo5.part_id = department5.id
					# department5右邊全部顯示
				
					select * from userinfo5 innder join department5 on userinfo5.part_id = department5.id
					將出現null時一行隱藏(即兩表中不對應的專案,這些專案就會隱藏)
					
					select * from 
						department5 
					left join userinfo5 on userinfo5.part_id = department5.id
					left join userinfo6 on userinfo5.part_id = department5.id	
			
			select count(id) from userinfo5;  計算表的資料行個數

上述取*會出錯,因為會有相同的列名重複,因此

					select 
						score.sid,
						student.sid 
						from 
					score

						left join student on score.student_id = student.sid

						left join course on score.course_id = course.cid

						left join class on student.class_id = class.cid

						left join teacher on course.teacher_id=teacher.tid