SQL连接三张表;表 1 的返回值,其中表 2 中的所有实例都具有相同的字段值

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

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

表一

<表类="s-表"> <头> 订单 状态 <正文> 001 一个 002 一个 003 B 004 B 005 一个

表2

<表类="s-表"> <头> 盒子 状态 订单 装运 <正文> 1 X 001 1 2 X 001 2 3 X 002 1 4 X 003 2 5 X 003 2 6 是 004 1 7 X 004 2 8 X 004 1 9 是 005 1

表3

<表类="s-表"> <头> 装运 状态 <正文> 1 C 2 一个

我需要从表 1 中选择状态为“A”的所有订单,并绑定(bind)到表 2 中的框,其中订单的所有框都处于状态“X”并绑定(bind)到表 3 中的装运处于状态“C”。

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

<表类="s-表"> <头> 订单 <正文> 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'

                                                             

最佳答案

您可以使用聚合,并在 t2t3 上使用 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/

相关文章:

sql - 如何在同一查询中多次引用单个表?

python - 分析异常: Using PythonUDF in join condition of join type LeftSemi is not supported

mysql - 将一个表中的多个值减去另一表中的另一个值

r - dplyr:根据聚合函数结果过滤行

json - 使用动态键和 json 值构建 JSON 对象

MYSQL select查询使用count(*)

mysql - 优化 MySQL 查询时出现问题

sql - 配置单元中 `load data inpath ` 和 `location` 之间的区别?

mysql - Django : select all columns when innerjoin using extra without foreignkey

sql - 如何在 MSSQL 中使用聚合函数更新表中的两列?