【问题标题】:results of a sub table in the top level query顶级查询中子表的结果
【发布时间】:2014-02-13 16:19:52
【问题描述】:

不确定如何命名,因此请随时重新命名。

我有两个具有一对多关系的表。

表1

|ID|NAME|...|

表2

|ID|Table1_ID|StartDate|EndDate|

我正在尝试编写一个查询,给定日期将返回以下内容

|TABLE1.ID|TABLE1.NAME|are any rows of table 2 in date|

我在表 1 和表 2 之间有一对多。我想将日期传递给查询。如果表 2 中的许多关系中的任何一个的开始日期 传入日期或结束日期为空,那么我希望结果的第 3 列为真。否则我希望它是假的。

考虑这个例子

|ID|NAME|...|
| 1|APPLE| ...|
| 2|PEAR| ...|

表2

|ID|Table1_ID|StartDate|EndDate|
|1|1|01-01-2014|null|
|2|1|01-01-2014|01-02-2014|
|3|2|01-01-2014|01-02-2014|
  • 如果我在 2014 年 1 月 1 日通过,那么我希望两行 ID 为 1 和 2 并且都为真(所有行都匹配)
  • 如果我在 2014 年 1 月 3 日通过,那么我预计两行 ID 1 为真(第一行匹配)和 ID 2 为假(因为第三行在此日期之外)

我正在尝试在 SQL 中执行此操作以最终转换为 JPA。如果有任何 JPA 函数可以做到这一点,那么很高兴知道。否则我会做一个原生查询

任何指针都会很棒!

谢谢

【问题讨论】:

  • 我没有在你的示例数据中看到任何日期为 01-03-2014
  • 您是否需要在输出中返回“FALSE”行,或者如果输出仅限于“TRUE”行,这是您想要的吗?
  • @Mihai 确实没有 01-03-2014,空结束日期意味着未来的永远,所以应该接受这个
  • @ShWiVeL true 和 false 行是必需的。感谢观看
  • 好的只是检查,因为在我给出的查询中,如果您只关心符合您条件的行,您可以省略联合/第二个查询。

标签: sql oracle hibernate jpa


【解决方案1】:

这应该给你你想要的:

select x.*, 'PASS' as checker
  from table1 x
 where exists
 (select 'x'
          from table2 y
         where y.table1_id = x.table1_id
           and y.startdate <= '01-01-2014'
           and (y.enddate >= '01-01-2014' or y.enddate is null))
union all
select x.*, 'FAIL' as checker
  from table1 x
 where not exists
 (select 'x'
          from table2 y
         where y.table1_id = x.table1_id
           and y.startdate <= '01-01-2014'
           and (y.enddate >= '01-01-2014' or y.enddate is null))

【讨论】:

    【解决方案2】:

    我不知道我是否理解你的问题。 所以,请耐心等待... ;)

    试试这样的:

    select t1.id, t1.name,
           case when t2.Table1_ID is null
                then 'false'
                else 'true' end as boolean_value
    from Table1 t1,
         (select distinct Table1_ID
          from Table2
          where yourdate >= StartDate
             and (yourdate <= EndDate or EndDate is null) t2
    where t1.id = t2.id (+);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-15
      • 1970-01-01
      • 2013-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多