SQL 三表连接

标签 sql join left-join

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

我正在尝试编写一个查询,返回有关股票的所有信息以及上次更新的时间。我想根据参数@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/

相关文章:

mysql - SQL 连接从三个表获取每月总工资

php - 尝试添加表时出现错误#1064

mysql - 用来自 2 个不同表的相应值替换列的值

MySQL 左外连接多张表

MySQL 多对多表连接性能慢

sql - 是否可以使用sql实现DFS(深度优先搜索)?

sql - 使用sql批量插入特定值

mysql - SQL 2 Left Join 带计数的查询

mysql 连接只有 1 个 id 的行

mysql - 使用 NULL 字段连接不存在的行的 SQL 查询