在Join中测试空子查询

时间:2012-03-21 20:55:40

标签: mysql sql jpa

我有一个带有非空日期字段的事件表。根据数据透视日期和偏移量,查询必须返回接下来的2个事件。

这是我正在尝试构建的查询:

SELECT e.* FROM Events as e
JOIN (
    -- latest event before pivot date, with offset
    SELECT * FROM Events where date < :dateRef
        ORDER BY date DESC, id DESC LIMIT :offset,1
) as eLatest
-- depending on :dateRef and :offset, eLatest can be empty!
-- If eLatest is empty, the join should produce all rows from Events table.
-- "eLatest is null" gives an error... How can I do it?
ON e.date > eFirst.date  || (e.date = eFirst.date && e.id >= eFirst.id)
ORDER BY e.date, e.id LIMIT 2

按日期ASC排序时有以下事件序列(没有相同的日期以保持简单): e0 - e1 - e2 - ... - e10

这是一些理想的结果:

  • :dateRef = e2.date,:offset = 0:[e1,e2]
  • :dateRef = e2.date,:offset = 1:[e0,e1]
  • :dateRef = e2.date,:offset&gt; 1:[e0,e1]&lt; ---不起作用,不返回行
  • :dateRef&lt; = e0.date,:offset =? :[e0,e1]&lt; ---不起作用,不返回行
  • :dateRef = e5.date,:offset = 2:[e2,e3]
  • :dateRef&gt; e10.date,:offset = 0:[e10]
  • :dateRef&gt; e10.date,:offset = 2:[e8,e9]

我遇到的问题是,当子查询eLatest为空时,连接永远不会匹配。当eLatest为空时,我无法弄清楚如何放弃连接条件。

最终查询必须在JPQL或JPA标准中可行(所以没有UNIONS!我已经有一个与UNION一起工作的查询,并且我试图摆脱它......)

1 个答案:

答案 0 :(得分:3)

RIGHT JOIN解决方案会做什么?

SELECT e.* FROM Events as e
JOIN (
    -- latest event before pivot date, with offset
    SELECT COALESCE(ev.date, b.date), COALESCE(ev.id, b.id)
    FROM (
        SELECT * FROM Events where date < :dateRef
        ORDER BY date DESC, id DESC LIMIT :offset,1
    ) ev
    RIGHT JOIN (
        SELECT CAST('1900-01-01' AS date) AS date, 0 AS id
    ) AS b ON 1=1
) as eFirst
ON e.date > eFirst.date  || (e.date = eFirst.date && e.id >= eFirst.id)
ORDER BY e.date, e.id LIMIT 2