如何避免两次连接到同一维表

时间:2018-09-10 11:08:55

标签: sql postgresql

我有task_instances表,task_id, end_time , start_time

end_timestart_time链接到time_table,其中包含“军用小时”格式(24小时,范围为0 -23)。

我想知道each tasks start time and end_time belong to the same military hour group ( there are 6 groups , each containing 4 hours)所在的所有任务。

  select (floor(td1.military_hour/4)*4) as td1_military_hour_group, 
  (floor(td2.military_hour/4)*4) as td2_military_hour_group, wk_id 
  from task_instances t1
  inner join time_table td1 on t1.end_time = td1.time_id
  inner join time_table td2 on t1.start_time = td2.time_id 
  where  td1_military_hour_group = td2_military_hour_group

是否需要加入same time_table twice。我们可以改善查询,甚至查询看起来正确吗?

1 个答案:

答案 0 :(得分:1)

您不能在WHERE子句中使用派生值td1_military_hour_grouptd2_military_hour_group,否则会出现错误,例如“'where子句'中的未知列'td1_military_hour_group'”。您需要在WHERE子句中重复计算:

select wk_id,
       (floor(td1.military_hour/4)*4) as td1_military_hour_group, 
       (floor(td2.military_hour/4)*4) as td2_military_hour_group
  from task_instances t1
  inner join time_table td1
    on t1.end_time = td1.time_id
  inner join time_table td2
    on t1.start_time = td2.time_id 
  where (floor(td1.military_hour/4)*4) = (floor(td2.military_hour/4)*4)

否则使用通用表表达式:

WITH cteTime_groups AS (SELECT time_id,
                               floor(military_hour/4)*4 AS military_hour_group
                          FROM time_table)
select wk_id,
       td1.military_hour_group as td1_military_hour_group, 
       td2.military_hour_group as td2_military_hour_group
  from task_instances t1
  inner join cteTime_groups td1
    on t1.end_time = td1.time_id
  inner join cteTime_groups td2
    on t1.start_time = td2.time_id 
  where td1.military_hour_group = td2.military_hour_group

SQLFiddle here