• LeetCode从不订购的客户SQL


    某网站包含两个表,Customers 表和 Orders 表。编写一个 SQL 查询,找出所有从不订购任何东西的客户。

    Customers 表:

    +----+-------+
    | Id | Name |
    +----+-------+
    | 1 | Joe |
    | 2 | Henry |
    | 3 | Sam |
    | 4 | Max |
    +----+-------+


    Orders 表:

    +----+------------+
    | Id | CustomerId |
    +----+------------+
    | 1 | 3 |
    | 2 | 1 |
    +----+------------+


    例如给定上述表格,你的查询应返回:

    +-----------+
    | Customers |
    +-----------+
    | Henry |
    | Max |
    +-----------+

    解法一:

    # Write your MySQL query statement below
    select Name as Customers from Customers where Id not in (select CustomerId from Orders)

    解法二:比解法一效率高

    # Write your MySQL query statement below
    select Name as Customers from Customers where not exists (select CustomerId from Orders where Orders.CustomerId = Customers.Id)

    备注:

    not in 存在隐患,如果查询的 CustomerId 为 null 时,就会查询结果错误。

    not exists 可避免 not in 上面问题

    解法三:连接

    # Write your MySQL query statement below
    select Name as Customers from Customers as a left join Orders as b on a.Id = b.CustomerId where b.Id is null

    做连接后表如下,然后做筛选。便于理解。

    Id
    Name
    Id
    CustomerId
    1
    Joe
    2 1
    2
    Henry
    null null
    3
    Sam
    1 3
    4
    Max
    null null

  • 相关阅读:
    python2.7之打飞机(文末附素材链接)
    python画小猪佩奇
    什么叫递归
    DIV居中的几种方法
    什么是控制反转
    上传图片及时预览
    MVC与三层的区别
    From表单提交刷新页面?
    文件上传之form表单篇
    文件上传之伪Ajax篇
  • 原文地址:https://www.cnblogs.com/huangzs/p/14178655.html
Copyright © 2020-2023  润新知