關於MySQL的多表查詢 外來鍵

2021-08-21 11:33:26 字數 426 閱讀 5315

1.關於外來鍵:

1.1    什麼是外來鍵:

用於建立主表與從表之間關係的鍵,存在於從表中。

1.2    外來鍵的特點:

(1)從表中外鍵的值是對主表主鍵的引用。

(2)外來鍵型別必須與主鍵型別一致。

1.3    從表中有外來鍵,主表與從表還是沒有關聯,如何建立聯絡呢?

語句:alter table 從表 add [constraint] [外來鍵名稱] foreign key (從表外來鍵欄位名)references 主表 (主表主鍵)

舉例:主表:category  主鍵:cid  

從表:product    外來鍵:category_id

語句:alter table product add foreign key(category_id) references category(cid);

mysql外來鍵查詢

當我們想檢視乙個資料庫表有多少其他表通過外來鍵依賴這個表的時候,可以通過視覺化的工具來看,當沒有工具可以使用的時候,可以通過如下的sql查詢來完成 select concat table name,column name as foreign key concat referenced table ...

如何繫結外來鍵實現多表查詢

例如有兩個表分別為 book 書籍 與 publisher 出版社 create table publisher 建立table publisher id char 36 primary key,name varchar 30 not null,address varchar 120 create ...

mysql的外來鍵級聯查詢 mysql外來鍵使用和級聯

如下面的 idint not null auto increment primary key,jobidint not null,studentidint not null,foreign key studentid referencesstudent id foreign key jobid re...