比较2表之间没有公共列的数据

时间:2014-10-01 10:29:45

标签: sql

我有2个表。我的第一个表只有列(即DATE),单行数据和 第二个表有3列(cost,startdate,enddate),包含多行数据。只有table2.startdate和table2.enddate Intervel之间存在table1.date时才需要获取table2.cost值。

任何人都可以告诉我查询上面关于sql

的情况

1 个答案:

答案 0 :(得分:0)

要为每个匹配日期从第二个表中获取一次记录,您可以加入表:

select
  t2.cost
from
  Table2 t2
  inner join Table1 t1 on t1.theDate >= t2.startdate and t1.theDate < t2.enddate

要从第二个表中获取匹配的记录,即使多个日期与第一个表匹配,也可以使用exists

select
  t2.cost
from
  Table2 t2
where
  exists (
    select *
    from Table1 t1
    where t1.theDate >= t2.startdate and t1.theDate < t2.enddate
  )

注意:我在比较中使用了>=<运算符,假设startdate具有包容性且enddate是独占的。如果enddate包含<=,您可以使用<运算符代替between,或使用{{1}}运算符。