SQLite-外键约束/表链接查询

外键约束:

表一的某个字段关联到表二的某个字段

例子:

国家表: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

转载于:https://www.cnblogs.com/Eazy/p/5232141.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值