1. 内连接查询

说明:组合两个表中的记录,返回关联字段相符的记录,也就是返回两个表的交集部分。

SELECT * FROM t_sample_g2 a inner JOIN  t_sample_pg1 b on a.id= b.id

 

2. 左连接查询

说明: left join 是left outer join的简写,它的全称是左外连接,是外连接中的一种。 左(外)连接,左表的记录将会全部表示出来,而右表只会显示符合搜索条件的记录。右表记录不足的地方均为NULL。

SELECT * FROM t_sample_g2 a left JOIN  t_sample_pg1 b on a.id= b.id

 

3. 右连接

说明:right join是right outer join的简写,它的全称是右外连接,是外连接中的一种。与左(外)连接相反,右(外)连接,左表只会显示符合搜索条件的记录,而右表的记录将会全部表示出来。左表记录不足的地方均为NULL。

SELECT * FROM t_sample_g2 a right JOIN  t_sample_pg1 b on a.id= b.id

 

4. 全连接

关键字:union /union all

 

语句:(select colum1,colum2...columN from tableA ) union (select colum1,colum2...columN from tableB )
或 (select colum1,colum2...columN from tableA ) union all (select colum1,colum2...columN from tableB );

 

union语句注意事项

  1. 通过union连接的SQL它们分别单独取出的列数必须相同;
  2. 不要求合并的表列名称相同时,以第一个sql 表列名为准;
  3. 使用union 时,完全相等的行,将会被合并,由于合并比较耗时,一般不直接使用 union 进行合并,而是通常采用union all 进行合并;
  4. 被union 连接的sql 子句,单个子句中不用写order by ,因为不会有排序的效果。但可以对最终的结果集进行排序;
(select id,name from A order by id) union all (select id,name from B order by id); //没有排序效果
(select id,name from A ) union all (select id,name from B ) order by id; //有排序效果

 

4.1. UNION

union :对两个结果集做合并操作,会根据结果集做去重操作,效率稍微低一些。

SELECT * FROM t_sample_g2
UNION
SELECT * FROM t_sample_g3

 

4.2. UNION All

union all :对两个结果集做合并操作,不包含去重操作,效率高一些;

SELECT * FROM t_sample_g2
UNION All
SELECT * FROM t_sample_g3