SQL Join with >= or between 逻辑
SQL Join with >= or between logic
我有两个 table 看起来像这样。
Table 1:
video_ref_raw_media_id | start_seconds | end_seconds | step
ABC001 | 0:00 | 0:30 | 1
ABC001 | 0:31 | 1:30 | 2
ABC001 | 1:31 | 2:30 | 3
ABC002 | 0:00 | 0:35 | 1
ABC002 | 0:36 | 1:46 | 2
ABC002 | 1:47 | 2:44 | 3
Table 2:
video_ref_raw_media_id | start_seconds | end_seconds | label
ABC001 | 0:10 | 0:11 | green
ABC001 | 0:15 | 0:16 | black
ABC001 | 1:45 | 1:46 | green
ABC002 | 0:20 | 0:21 | red
我想加入 table 1 到 table 2 基于 1 video_ref_raw_media_id 和 2 基于 table 1 中的步骤。唯一的方法这是如果在 table 2 中应用的标签出现在 table 1 中步骤的时间范围内(在 start_seconds 和 end_seconds 之间)。我希望这是有道理的。
我认为 sql 看起来像
Select * from
"Table 1"
LEFT JOIN "Table 2" on "Table 1".video_ref_raw_media_id="Table 2".video_ref_raw_media_id and (Table2.start_seconds>=Table1.start_seconds and Table2.end_seconds<=Table1.end_seconds)
但是,这不起作用。有什么想法吗?
理想输出:
video_ref_raw_media_id | start_seconds | end_seconds | step | label
ABC001 | 0:00 | 0:30 | 1 | green
ABC001 | 0:00 | 0:30 | 1 | black
ABC001 | 0:31 | 1:30 | 2 | null
ABC001 | 1:31 | 2:30 | 3 | green
ABC002 | 0:00 | 0:35 | 1 | red
ABC002 | 0:36 | 1:46 | 2 | null
ABC002 | 1:47 | 2:44 | 3 | null
你应该摆脱半列,它会起作用,并转换为 int:
Select * from
"Table 1"
LEFT JOIN "Table 2" on "Table 1".video_ref_raw_media_id="Table 2".video_ref_raw_media_id
and cast((replace(Table2.start_seconds,':','') as int)>=cast(replace(Table1.start_seconds,':','') as int)
and cast(replace(Table2.end_seconds,':','') as int)<=cast(replace(Table1.end_seconds,':','') as int))
我有两个 table 看起来像这样。
Table 1:
video_ref_raw_media_id | start_seconds | end_seconds | step
ABC001 | 0:00 | 0:30 | 1
ABC001 | 0:31 | 1:30 | 2
ABC001 | 1:31 | 2:30 | 3
ABC002 | 0:00 | 0:35 | 1
ABC002 | 0:36 | 1:46 | 2
ABC002 | 1:47 | 2:44 | 3
Table 2:
video_ref_raw_media_id | start_seconds | end_seconds | label
ABC001 | 0:10 | 0:11 | green
ABC001 | 0:15 | 0:16 | black
ABC001 | 1:45 | 1:46 | green
ABC002 | 0:20 | 0:21 | red
我想加入 table 1 到 table 2 基于 1 video_ref_raw_media_id 和 2 基于 table 1 中的步骤。唯一的方法这是如果在 table 2 中应用的标签出现在 table 1 中步骤的时间范围内(在 start_seconds 和 end_seconds 之间)。我希望这是有道理的。
我认为 sql 看起来像
Select * from
"Table 1"
LEFT JOIN "Table 2" on "Table 1".video_ref_raw_media_id="Table 2".video_ref_raw_media_id and (Table2.start_seconds>=Table1.start_seconds and Table2.end_seconds<=Table1.end_seconds)
但是,这不起作用。有什么想法吗?
理想输出:
video_ref_raw_media_id | start_seconds | end_seconds | step | label
ABC001 | 0:00 | 0:30 | 1 | green
ABC001 | 0:00 | 0:30 | 1 | black
ABC001 | 0:31 | 1:30 | 2 | null
ABC001 | 1:31 | 2:30 | 3 | green
ABC002 | 0:00 | 0:35 | 1 | red
ABC002 | 0:36 | 1:46 | 2 | null
ABC002 | 1:47 | 2:44 | 3 | null
你应该摆脱半列,它会起作用,并转换为 int:
Select * from
"Table 1"
LEFT JOIN "Table 2" on "Table 1".video_ref_raw_media_id="Table 2".video_ref_raw_media_id
and cast((replace(Table2.start_seconds,':','') as int)>=cast(replace(Table1.start_seconds,':','') as int)
and cast(replace(Table2.end_seconds,':','') as int)<=cast(replace(Table1.end_seconds,':','') as int))