• SQL Cookbook:操作多个表


    1、记录集的叠加

    使用union all

    union all包含重复的结果,union筛选掉重复项(可能需要排序)

    1 select * from film where film_id < 5
    2 union all
    3 select * from film where film_id > 995G

    2、组合相关的行

    1 select f.title, a.first_name 
    2 from film f, actor a, film_actor fa 
    3 where f.film_id = fa.film_id and a.actor_id = fa.actor_id and f.film_id = 10G

    以上连接方法是等值连接,这是内连接的一种。

    如果希望连接逻辑放在from子句中,那么可以使用join关键字

    1 select f.title, a.first_name 
    2 from film f join film_actor fa on f.film_id = fa.film_id join actor a on fa.actor_id = a.actor_id 
    3 where f.film_id = 10G

    4、or与null组合的坑

    在sql中,true or null结果是true,false or null结果是null,举例:

    1 mysql> select title from film where film_id not in (1,2,3,null)G
    2 Empty set (0.03 sec)

    原因是in查询等价于:

    1 mysql> select title from film where not (film_id = 1 or film_id = 2 or film_id = 3 or film_id = null)G
    2 Empty set (0.02 sec)

    其中where从句等价于:

    1 (false or false or null)

    最终答案是null。

    要解决这个问题,可以使用is判断null:

    1 mysql> select title from film where not (film_id = 1 or film_id = 2 or film_id = 3 or film_id is null)G

    5、left join

    A a left outer join B b

    返回A中所有行,B中匹配则返回,不匹配则为null

    6、n-1规则

    如果from子句有n个表,那么为了避免产生笛卡尔积,最少需要使用n-1个联接数

    7、full outer join on

    返回两个表中丢失的行以及所有匹配的行

    8、在运算和比较时使用null

    使用coalesce函数将null转换为一个可以用作标准值比较的真实值

  • 相关阅读:
    Http Get与Post的区别
    华为USG6000V防火墙简单配置案例
    华为USG6000V防火墙简单配置案例
    基于三层交换机的VRRP技术--MSTP、VRRP的综合运用
    ci test
    CI框架 default_controller 如何设置为:'目录/Controller' 转
    查看django版本的方法
    Django如何安装指定版本
    django学习--2 模板
    django学习--1
  • 原文地址:https://www.cnblogs.com/zcy-backend/p/6813482.html
Copyright © 2020-2023  润新知