gpt4 book ai didi

SQL 三表连接

转载 作者:行者123 更新时间:2023-12-04 23:47:23 24 4
gpt4 key购买 nike

我已经好几天没能解决这个问题了,我希望你能帮忙。

我正在尝试编写一个查询,返回有关股票的所有信息以及上次更新的时间。我想根据参数@date 过滤结果,只返回最新更新小于提供的@date 参数的股票。我还需要时间戳为 null 的股票,所以我知道这些股票需要更新。我正在使用以下三个表:

stocks
- id
- asset_id
- market_id
- name
- symbol
- IPOYear
- sector
- industry

updates
- id
- [timestamp]

stock_updates
- stock_id
- update_id

我一直在使用以下查询,它对我来说效果很好,直到我意识到如果库存没有更新它就不起作用

select * from stocks s
where @date < (
select top 1 u.timestamp from
updates u,
stock_updates su
where
s.id = su.stock_id and
u.id = su.update_id
order by u.timestamp desc
)

因此,经过一些研究后,我遇到了外连接,我认为这是我需要解决的问题,但我无法构建正确的查询。我最接近的是以下内容,但每次更新库存时它都会返回一条记录。预先感谢您的帮助!

这是我现在的位置:

select * from stocks s 
left outer join stock_updates su on s.id = su.stock_id
left outer join updates u on u.id = su.update_id
where u.[timestamp] < @date

最佳答案

select s.*, u.timestamp
from stocks s
left join
(select su.stock_id, MAX(u.timestamp) timestamp
from updates u
inner join stock_updates su
on u.id = su.update_id
group by su.stock_id
) as u
on s.id = u.stock_id
where u.[timestamp] is null or u.[timestamp] < @date

关于SQL 三表连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9345482/

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