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