MySQL入門(alter語法 與 外鍵)


MySQL入門(三)

字段的修改、添加、與刪除

修改表字段使用alter table語句,謹記!

create table tf1(
	id int primary key auto_increment,
    x int,
    y int
);

# 修改
alter table tf1 modify x char(4) default '';
alter table tf1 change y m char(4) default '';

# 增加
mysql>: alter table 表名 add 字段名 類型[(長度) 約束];  # 末尾
eg>: alter table tf1 add z int unsigned;

mysql>: alter table 表名 add 字段名 類型[(寬度) 約束] first;  # 首位
eg>: alter table tf1 add a int unsigned first;

mysql>: alter table 表名 add 字段名 類型[(寬度) 約束] after 舊字段名;  # 某字段后
eg>: alter table tf1 add xx int unsigned after x;

mysql>: alter table 表名 drop 字段名;  # 刪除字段
eg>: alter table tf1 drop a;

多表關系(外鍵)

外鍵基礎知識

"""
多表關系主要如下:
一對一:外鍵在任何一方都可以,此時外鍵要設置 唯一鍵
一對多:外鍵必須放在多的一方,此時外鍵值不唯一
多對多:一定要創建第三張表(關系表),每一個外鍵值不唯一,看可以多個外鍵建立聯合唯一
"""
# 1、外鍵的 字段名 可以自定義(名字隨意),通常命名規范(關聯表_關聯字段)

# 2、外鍵要通過 foreign key 語法建立表與表之間的關聯

# 3、[constraint 外鍵名 ]foreign key(所在表的外鍵字段) references 關聯表(關聯字段)
# eg:foreign key(detail_id) references author_detail(id)

# 4、級聯關系
#	級聯更新 on update cascade
# 	級聯刪除 on delete cascade

# 重點:外鍵字段本身可以唯一或不唯一,但是外鍵關聯的字段一定唯一

"""
非級聯的兩張關系表,若數據已經被從表引用,則主表的那條數據無法更新或刪除,只有先刪了從表的數據才能操作主表的數據;
有級聯的兩張關系表,主表的數據更新或刪除,會同時影響從表,會跟着一起更新或刪除。
"""

"""
了解內容:(除級聯外的其他reference_option)
set null:從父表中刪除或更新該行,並將子表中的一個或多個外鍵列設置為NULL。ON DELETE SET NULLON UPDATE SET NULL。

restrict:拒絕父表的刪除或更新操作。指定 RESTRICT(或NO ACTION)與省略ON DELETEor ON UPDATE子句相同。

no action :標准SQL中的關鍵字。在MySQL中等效於RESTRICT。

set default: 
"""

設置外鍵

# 建表語句
CREATE TABLE parent (
    id INT NOT NULL,
    PRIMARY KEY (id)
) ENGINE=INNODB;

CREATE TABLE child (
    id INT,
    parent_id INT,
    INDEX par_ind (parent_id),
    FOREIGN KEY (parent_id)
        REFERENCES parent(id)
        ON DELETE CASCADE
);

# 升級版  product_order表具有其他兩個表的外鍵。一個引用product的兩個字段,一個引用customer的一列:
CREATE TABLE product (
    category INT NOT NULL, id INT NOT NULL,
    price DECIMAL,
    PRIMARY KEY(category, id)
)   ENGINE=INNODB;

CREATE TABLE customer (
    id INT NOT NULL,
    PRIMARY KEY (id)
)   ENGINE=INNODB;

CREATE TABLE product_order (
    no INT NOT NULL AUTO_INCREMENT,
    product_category INT NOT NULL,
    product_id INT NOT NULL,
    customer_id INT NOT NULL,

    PRIMARY KEY(no),
    INDEX (product_category, product_id),
    INDEX (customer_id),

    FOREIGN KEY (product_category, product_id)
      REFERENCES product(category, id)
      ON UPDATE CASCADE ON DELETE RESTRICT,

    FOREIGN KEY (customer_id)
      REFERENCES customer(id)
)   ENGINE=INNODB;

添加外鍵

如果我們忘記設置外鍵也可以后續添加(如果沒有那個字段就需要先手動添加):

ALTER TABLE tbl_name
    ADD [CONSTRAINT [symbol]] FOREIGN KEY
    [index_name] (col_name, ...)
    REFERENCES tbl_name (col_name,...)
    [ON DELETE reference_option]
    [ON UPDATE reference_option]

刪除外鍵

我們可以使用alter table語法來刪除外鍵:

ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol;

若是不知道外鍵名稱可以使用show create table語法來查看:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM