连接2表的最佳方法是什么?

dohp0rv5  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(362)

我有个问题。
我想找到一个新用户谁在24小时内搜索注册。
我有两个表,这意味着用户加入和搜索历史。
连接这些表的最佳方法是什么?(搜索的表是kst时区,用户注册表是utc时区)
我写了两个查询,你觉得这样行吗?我不能附加图像,所以我上传它作为一个链接。
搜索历史表
历史记录表
用户注册表
用户注册表
预期产量
预期产量
我的查询
1.

select date(t1.kst_created_time), count(distinct t1.id)
from table1 as t1
inner join (
    select id, utc_created_time + interval '9' hour as utc_to_kst_created_time
    from table2
)as t2
    on t1.user_id = t2.id
    and date_diff('second', t2.utc_to_kst_created_time, t1.kst_created_time) <= 86400
group by 1
select
    dt, count(distinct id)
from (
    select
            date(t1.kst_created_time) as dt,
            t1.id as id,
            date_diff('second', t2.user_join_time_kst, t1.kst_created_time ) as second_diff
    from table1 as t1
    inner join (
        select id, utc_created_time + interval '9' hour as utc_to_kst_created_time
        from table2
    ) as t2
        on t1.user_id = t2.id
        and t1.kst_created_time >= t2.utc_to_kst_created_time
) as second_diff_of_t1_and_t2_created_time
where second_diff <= 86400
group by 1
oipij1gg

oipij1gg1#

我建议你 exists 而不是加入(因为您从 join 和时区转换 at time zone .
假设时间戳存储为 timestamp with time zone :

select date(t1.kst_created_time) kst_created_date, count(distinct t1.id) no_
from table1 t1
where exists (
    select 1
    from table2 t2
    where 
        t2.id = t1.user_id 
        and t2.utc_created_time <= t1.kst_created_time at time zone 'UTC' + interval '1' day
)
group by 1

此查询不需要将时间戳从 table2 ,因此它应该利用 table2(id, utc_created_time) .

相关问题