我需要将三个表连接在一起。具体来说,表 1 需要连接到表 2,表 2 连接到表 3。我需要从表 1 返回值,其中表 2 中表 1 中选择的值的所有实例都有一个具有某个值的字段,然后由我进一步选择加入表 3。给出示例可能更容易。
表一
表2
表3
我需要从表 1 中选择状态为“A”的所有订单,并绑定(bind)到表 2 中的框,其中订单的所有框都处于状态“X”并绑定(bind)到表 3 中的装运处于状态“C”。
我的最终结果应该返回以下内容:
我有以下内容,但它不是 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'
最佳答案
您可以使用聚合,并在 t2
和 t3
上使用 having 子句进行过滤:
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
关于SQL连接三张表;表 1 的返回值,其中表 2 中的所有实例都具有相同的字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65203788/