gpt4 book ai didi

ruby-on-rails - 我使用哪个 SQL Join 来查看一个表中不存在于同一个表的集合中的结果?

转载 作者:行者123 更新时间:2023-11-29 13:10:12 24 4
gpt4 key购买 nike

我有一个巨大的表,其中每个月都会生成记录,结果用 month_of 列标记。我需要每个月比较这些 month_of 结果集以找到新的激活(本月存在但上个月不存在的新记录)

目标:从当前月份获取一组结果,其中唯一 ID 在上个月不存在。

解释:

上个月(三月),我有 10 条记录标记为 status="ACTIVE",month_of "MARCH"

本月(4 月),我有 11 条记录标记为 status="ACTIVE",month_of "APRIL"

我已经尝试过这样的事情:如果 ta1 = 当前月份的报告,而 ta2 = 上个月的报告

SELECT id FROM table ta1
LEFT OUTER JOIN table ta2
ON ta1.status = ta2.status
WHERE ta1.month_of = #{current_month}
AND ta2.month_of = #{last_month}
AND ta1.status = 'ACTIVE'
AND ta2.id IS null

我需要的查询将返回 month_of“APRIL”的 1 条新记录,但 month_of“MARCH”结果中不存在。

任何人都可以指出我要使用的正确连接以获得我正在寻找的东西吗?该解决方案将应用于具有近十亿条记录的表。

最佳答案

选择编号
来自 ta1
其中 month_of = (current_month)
并且 id 不在(从 ta1 中选择 id,其中 month_of =(last_month))
和状态('事件')

或者你可以这样做:

选择a.id
from(select id, month_of from ta1 where month_of = (current_month) and status = 'Active'
)a
left join (select id, month_of from ta1 where month_of = (last_month)
)b on a.id != b.id

关于ruby-on-rails - 我使用哪个 SQL Join 来查看一个表中不存在于同一个表的集合中的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55909266/

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