外鍵約束:
表一的某個字段關聯到表二的某個字段
例子:
國家表:t_country
地區表:t_area
若t_area表的country_id設置外鍵約束,關聯了t_country表的id字段。那么從t_area表中country_id=1,表示China這個國家,以此類推。
注意事項:
1.若設置了外鍵關聯,無法輸入不存在的外鍵鍵值,如:t_area表country_id字段無法輸入4,因為t_country表的id字段不存在4
2.無法刪除已被關聯的外鍵鍵值,如:無法刪除t_country表的id=2該條數據,因為t_area表country_id=2已經存在
設置約束:
1.表格約束:navicat->右擊t_area->design table
2.代碼約束:navicat-》右擊main-》new query
create table t_area (id integer primary key autoincrement, name text, country_id integer, constraint fk_class_id_t_country_id foreign key (country_id) references t_country (id));
表鏈接查詢:聯合多表進行查詢
如查詢中國國家有哪些地區
select a.name from t_area a,t_country c where a.country_id=c.id and c.name='China';
內連接:表鏈接查詢其中一種方式,但顯示兩表中匹配字段(a.country_id=c.id)的數據,不匹配字段(t_country表中有Thailand,而t_area中沒Thailand)數據不顯示
如查詢a.country_id=c.id,泰國國家沒顯示
select a.name ,c.name from t_area a inner join t_country c on a.country_id=c.id ;
左外連接:表鏈接查詢另外一種方式,以左表數據為主表。若左表匹配字段有數據,而右表匹配字段無數據,以左表為主輸出。
如以t_area為左表查詢a.country_id=c.id,左表中a.country_id字段只有china、England、American,因此Thailand不輸出
select a.name ,c.name from t_area a left outer join t_country c on a.country_id=c.id;
如以t_country為左表查詢a.country_id=c.id,左表中c.id包含Thailand,因此Thailand也會輸出,但a.country_id無該字段值,所以為NULL