gpt4 book ai didi

mysql - 仅从表连接中获取那些尚未达到其最终状态的记录

转载 作者:行者123 更新时间:2023-11-28 23:23:17 27 4
gpt4 key购买 nike

如果有两个表A和B:

Table A                    
id work_name
1 10001
2 10002

Table B
id work_id final_status
1 1 0
2 2 0
3 1 1

我必须只获取那些最终状态不是 1 的 work_id在上表中输出应为 2,因为 work_id 1 的 final_status 已达到 1。我已经尝试过查询,但它没有给我想要的结果

我的查询:

select B.work_id from A inner join B on A.id = B.work_id where final_status!=1

我的结果:

1 
2

我想排除 1,因为它已达到最终状态。

最佳答案

有多种方法可以产生所需的输出:

  • 在表A上加入表B两次
  • 加入表B一次,获取final_status的max(),并在having子句中过滤
  • in()not in() 子查询的组合
  • exists()not exists() 子查询的组合

我更喜欢最后一种方法,因为 exists()/not exists() 不必实际从表 B 中获取数据:

select A.*
from A
where exists(select 1 from B where B.work_id=A.id and B.final_status=0)
and not exists(select 1 from B where B.work_id=A.id and B.final_status=1)

关于mysql - 仅从表连接中获取那些尚未达到其最终状态的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40545187/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com