数据库操作(三)

1、内连接:inner join

  基本语法:select  a.列名 from 表1 a inner join 表2 b on a.id =b.id [and ... inner join 表3 c on ...] where a.name = '值';

2、外连接:

  (1)左外连接:left join

          select  a.列名 from 表1 a left join 表2 b on a.id =b.id and b.列名= '值'[ inner join 表3 c on ...] where a.name = '值';

  (2)右外连接:right join

          select  a.列名 from 表1 a right join 表2 b on a.id =b.id and  b.列名= '值'[ inner join 表3 c on ...] where a.name = '值';

  注:and后内容与只与表2 有关

3、合并结果集

  (1)去重合并:union

          select column_names  from 表1 union select column_names from 表2;

    注:表1与表2必须:列的数量相同、列的顺序相同、列的类型相同

      表1与表2可以:列名不同,直接加入数据(select 5 as 列名s from 表名)

      当列出现别名时:select column_names a  from 表1 union select column_names  b from 表2;

              输出结果只与a有关

            

  (2)完全合并:union all

     select column_names a  from 表1 union all select column_names  b from 表2 order by 列名;

    注:order by 写在最后

4、except :去掉表2中存在的与表1相同的数据

      select column_names a  from 表1 except select column_names  b from 表2;

  intersect:取交集

      select column_names a  from 表1 intersect select column_names  b from 表2;

原文地址:https://www.cnblogs.com/Yida-Tingting/p/4434358.html