外键约束:
表一的某个字段关联到表二的某个字段
例子:
国家表: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