MySQL資料庫基礎知識四(外來鍵和引用)
阿新 • • 發佈:2018-12-11
級聯刪除,級聯更新
外來鍵維護資料的一致性。
下面是幾條術語:
父表:包含原始鍵值的表。
子表:引用了父表中鍵值的相關表。
建立父表和子表關聯案例
父表:
create table parent
{
par_id INT NOT NULL,
PRIMART KEY (par_id);
}ENGINE = INNODB;
子表
create table child
{
par_id int not null,
child_id int not null,
primary key (par_id,child_id),
foreign key (par_id) references parent (par_id),
ON DELETE CASCADE
ON UPDATE CASCADE
}ENGINE = INNODB;
上面的子表的定義會使對父表進行更改和刪除時字表的資料也會隨著改變,若父表裡沒有某個id值則子表中不能相應的插入該id值得資料。
建立父表和子表不關聯案例
create table child
{
par_id int not null,
child_id int not null,
UNIQUE (par_id,child_id),
foreign key (par_id) references parent (par_id),
ON DELETE SET NULL
ON UPDATE SET NULL
}ENGINE = INNODB;
當插入父表刪除和更改par_id值時,子表對應的值id值改為NULL。
使用FULLTEXT搜尋
select * from tb_name where MATCH(columns_name) AGAINST('time');