篩選條件、聚合分組、連接查詢
mysql三:表結(jié)構(gòu)修改、約束條件、python交互
一.表結(jié)構(gòu)修改 --- alter
1.修改表名: alter table 原名 rename to 新名;
2.修改字段名:alter table 表名 change 原名 新名 類型; 要寫類型
alter table tb change n2 age int; 不能修改!!
n2是char類型, 只能同一類型修改 (沒(méi)有數(shù)據(jù)可以修改)
3.修改字段類型 -- modify
alter table tb modify name2 char(10);
4.添加字段
alter table 表名 add 列名 類型;
日期字段: alter table tb add tdate datetime;
插入數(shù)據(jù):insert tb values(1, 'zs', 18, '2021-12-14 23:24:25');
返回當(dāng)前的日期時(shí)間: now()
insert tb values(1, 'zs', 18, now());
enum字段:alter table tb add sex enum('F', 'M'); F/M是固定值,自己設(shè)置
插入數(shù)據(jù):insert into tb values(2, 'we', 18, now(), 'F');
5.刪除字段:
alter table tb drop sex;
二、約束條件
1.默認(rèn)default
create table a(id int default 9);
2.非空 not null
create table c(id int not null);
3.唯一 unique key
create table d(id int unique key);
4.主鍵 primary key 非空+唯一 每張表最多只允許一個(gè)主鍵
create table a(id int primary key, name varchar(20));
4.1 自增長(zhǎng) auto_increment
create table b(
-> id int auto_increment,
-> name varchar(20),
-> primary key(id)
-> );
insert b values(), (),(); id會(huì)自動(dòng)增加
4.2 設(shè)定初始值
create table c(id int auto_increment, primary key(id))auto_increment=10;
insert b values(), (),(); id會(huì)自動(dòng)增加 ,從10開(kāi)始
5.外鍵: foreign key
假設(shè)一個(gè)字段是某個(gè)表的外鍵時(shí),那么該字段必須是主鍵
作用: 使兩張表關(guān)聯(lián),保證數(shù)據(jù)的一致性和實(shí)現(xiàn)一些級(jí)聯(lián)操作
a表: id int 主鍵 ; name varchar(20)
create table a(id int primary key, name varchar(20));
b表: b_id int 主鍵; age int; foreign key(b_id) references a(id)
references 關(guān)聯(lián)的是表名及字段
foreign key(b_id) 中的b_id是外鍵id, 有外鍵的是從表
create table b(b_id int primary key, age int, foreign key(b_id) references a(id));
插入數(shù)據(jù):
外鍵里面能夠插入的一定是主鍵里面有的數(shù)據(jù)
insert a values(1, 'Object'), (2, '自律的峰峰'), (3, '啦啦啦');
insert b values(1, 18), (2, 20), (3, 22);
insert b values(4, 24); 錯(cuò)誤,因?yàn)橹鞅韆表里面沒(méi)有id=4的值
添加數(shù)據(jù):先操作主表再去從表添加
刪除數(shù)據(jù):先刪除從表再去主表刪除
6.刪除主外鍵約束:
6.1刪除外鍵約束:
先獲取外鍵名再去刪除外鍵約束
查看表創(chuàng)建語(yǔ)句: show create table b;
出現(xiàn)的是:ConSTRAINT `b_ibfk_1` FOREIGN KEY (`b_id`) REFERENCES `a` (`id`)
b_ibfk_1是外鍵名,系統(tǒng)自動(dòng)分配
語(yǔ)法:alter table 表名 drop foreign key 外鍵名;
alter table b drop foreign key b_ibfk_1;
6.2 刪除主鍵約束
alter table a drop primary key;
如果跟其他表有關(guān)聯(lián),要先刪除從表的外鍵,再刪除主表的主鍵
6.3 主外鍵區(qū)別:
主鍵:唯一標(biāo)識(shí),不能有重復(fù),不能為空
外鍵:是另一個(gè)表的主鍵
三、python交互
import pymysql