【问题标题】:SQL Join Three Tables; Return Values from Table 1 where all instances in Table 2 have the same field valueSQL Join 三表;表 1 中的返回值,其中表 2 中的所有实例具有相同的字段值
【发布时间】:2021-03-20 01:28:47
【问题描述】:

我需要将三个表连接在一起。具体来说,表 1 需要加入表 2,表 2 加入表 3。我需要从表 1 返回值,其中表 2 中表 1 中选择的值的所有实例都具有某个值的字段,然后由我的进一步选择加入表 3。展示示例可能更容易。

表 1

Order Status
001 A
002 A
003 B
004 B
005 A

表 2

Box Status Order Shipment
1 X 001 1
2 X 001 2
3 X 002 1
4 X 003 2
5 X 003 2
6 Y 004 1
7 X 004 2
8 X 004 1
9 Y 005 1

表 3

Shipment Status
1 C
2 A

我需要从表 1 中选择状态为“A”的所有订单,并且与表 2 中的框相关联,其中订单的所有框都处于状态“X”并与表 3 中的货件相关联处于“C”状态。

我的最终结果应该返回以下内容:

Order
002

我有以下信息,但它不是 100% 准确,因为 Table2.Shipment 可以是空白值。我真正的问题是很难从表 1 中找到订单,其中表 2 中该订单的所有框都处于相同状态。

SELECT order
FROM table1
JOIN table2 ON table1.order = table2.order
WHERE table2.order NOT IN
(SELECT table2.order FROM table2
JOIN table3 ON table2.shipment=table3.shipment
WHERE table3.status = 'A')
AND table2.order IN
(SELECT table2.order FROM table2
JOIN table3 ON table2.order = table3.order
WHERE table3.status = 'C') 
AND table1.status = 'A'
AND table2.status = 'X'

                                                             

【问题讨论】:

    标签: sql inner-join aggregate-functions having-clause


    【解决方案1】:

    您可以使用聚合,并使用 having 子句过滤 t2t3

    select t1.orderid
    from table1 t1
    inner join table2 t2 on t2.orderid  = t1.orderid
    inner join table3 t3 on t3.shipment = t2.shipment
    where t1.status = 'A'
    group by t1.orderid
    having max(case when t2.status <> 'X' then 1 else 0 end) = 0 
       and max(case when t3.status <> 'C' then 1 else 0 end) = 0
    

    【讨论】:

    • 谢谢!效果非常好,也感谢您的快速响应!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 2018-10-05
    相关资源
    最近更新 更多