zoukankan      html  css  js  c++  java
  • 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转换为一个可以用作标准值比较的真实值

  • 相关阅读:
    Sysinternals Suite
    扩展Visual Studio Test Project:自定义TestClassAttribute
    扩展Visual Studio Test Project:自定义TestClassAttribute
    SQL Server Single-user Mode
    MAXDOP(max degree of parallelism)
    关于log4net
    Go 切片的一种有趣内存泄漏方式
    Go 中的内联优化
    优化 Golang 服务来减少 40% 以上的 CPU
    Go 编译器内部知识:向 Go 添加新语句-第 2 部分
  • 原文地址:https://www.cnblogs.com/zcy-backend/p/6813482.html
Copyright © 2011-2022 走看看