iOS简单的多表查询以及SQLite注意点

多表查询

假如有两张表:

表A:


表B:


这里我们是通过相同列名departmentNumber来进行条件查询相关信息:

1.内连接查询:返回的结果只有满足departmentNumber相等的结果

sql语句(有两种方式):

-->select a.name, b.name from A as a, B as b where a.departmentNumber = b.departmentNumber

-->select a.name, b.name from A as a inner join B as b on a.departmentNumber = b.departmentNumber

查询结果:

2.左外链接查询:返回的结果只和左边的表有关(这里假定A是左边的表),右边表如果没有对应值,就为NULL

sql语句:

-->select a.name, b.name from A as a left outer join B as b on a.departmentNumber= b.departmentNumber

返回结果:


3.右外链接查询:返回的结果只和右边的表有关(这里假定B是右表),那么如果左边表是没有对应值,就为NULL

sql语句:

-->select a.name, b.name from A as a right OUTER join B as b on a.departmentNumber = b.departmentNumber

返回结果:


4.完全外链接查询:想获取两个表所有信息,如果两个表内没有对应值的就用NULL表示

sql语句:

-->select a.name, b.name from B as b full OUTER join A as a on a.departmentNumber = b.departmentNumber

返回结果:


注意点:在sqlite中是不支持右外连接和完全外链接的,但是可以通过以下方式来进行连接:

1.sqlite中的右外连接:将左外连接的表换个顺序就可以了

-->select a.name, b.name from B as B left outer join A as A on a.departmentNumber = b.departmentNumber

返回结果:


2.sqlite中的完全外链接:用关键字union将两句连接起来进行合并

-->select a.name, b.name from B as b left OUTER A as a on a.departmentNumber = b.departmentNumber

UNION

select a.name, b.name from A as a left outer B as b on a.departmentNumber = b.departmentNumber

返回结果:


推荐阅读更多精彩内容