【问题标题】:SQL to fetch Data from 2 tables only using Join where we need empty records from second table as wellSQL 仅使用 Join 从 2 个表中获取数据,其中我们还需要来自第二个表的空记录
【发布时间】:2019-02-13 13:36:15
【问题描述】:

我们有一种情况,我们的存储过程的一部分需要填充一个 join 查询,其中有多个过滤器。我们只需要一个带有 join 的解决方案(在子查询中很容易实现,但我们的情况要求它是一个 join [因为过程后面有一个 where 子句])

我们有两张表 Customer 和 Order。我们需要排除 Customer 表的行,如果 Customer_id 存在 Order table & order_code = 10 & Customer.Grade = 3。并非强制所有 Customer_id 都存在于 Order 表中,但我们仍然需要在最终结果中.

   Customer Table                             OrderTable
Customer_id     Grade                   Customer_id     order_code 
 1                3                            1            10
 2                3                            1            40                                
 3                2                            2            50                        
 4                3                            3            30

*OrderTable 中可以存在多个 Customer_id

预期结果:

Customer_id     Grade
    2            3    
    3            2        
    4            3

【问题讨论】:

    标签: sql postgresql stored-procedures


    【解决方案1】:

    我认为这可能是您需要的,不确定我是否正确理解了这个问题。

    select c.id, c.grade from customer c left join customer_order o on (c.id = o.customer_id and o.order_code <> 10) where c.grade = 3

    如果 order_code 不是 10,这应该为您提供所有有订单的等级为 3 的客户。如果您想显示也没有任何订单的客户,请将其设为左连接。

    【讨论】:

      【解决方案2】:

      你可以这样表达逻辑:

      select c.*
      from customers c
      where not (grade = 3 and
                 exists (select 1
                         from orders o
                         where o.customer_id = c.customer_id and
                               o.order_code = 10
                        )
                 );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-20
        • 1970-01-01
        • 1970-01-01
        • 2010-12-21
        • 2023-03-24
        • 2018-07-11
        相关资源
        最近更新 更多