从同一个表中加入两个结果集?

时间:2014-05-21 03:49:23

标签: sql sqlite

我有一个SQLite数据库,它是PVR应用程序的一部分。其中一个表(epg_event)保存了电视节目的所有数据。

我正在尝试编写一个查询,它将在Now和Next的单个记录中返回Now / Next节目。

我可以很容易地单独查询。

Now查询本身就是这样......

SELECT now.channel_oid as _id,
       now.oid as now_oid,
       now.title as now_title,
       now.start_time as now_start_time,
       now.end_time as now_end_time
FROM epg_event now
WHERE  now.start_time <= datetime('now') AND now.end_time > datetime('now')
ORDER BY now.channel_oid

这很有效,在测试中我得到了我需要的东西。实施例...

_id      now_oid     now_title   now_start_time         now_end_time
10029    16365522    BBC News    2014-05-21 00:45:00    2014-05-21 05:00:00
10030    16365900    Making Art  2014-05-21 03:00:00    2014-05-21 04:00:00
...

Next查询本身就是这样......

SELECT next.channel_oid as _id,
       next.oid as next_oid,
       next.title as next_title,
       MIN(next.start_time) as next_start_time,
       next.end_time as next_end_time
FROM epg_event next
WHERE next.start_time > datetime('now')  
GROUP BY next.channel_oid

这也会为Next TV节目返回正确的结果。

我遇到的问题是我正在尝试将两个查询组合在一起,为每个通道返回一条记录,同时包含Now和Next数据,但我无法弄清楚如何做到这一点。我想我需要使用某种类型的JOIN,但是每当我尝试它时,我的SQLite工具都会不断出现错误。

理想情况下,我要做的是在每一行中获取一个_id列,并将now / next列合并到行中,以便我有以下列...

_id  now_oid  now_title  now_start_time  now_end_time  next_oid  next_title  next_start_time  next_end_time

是否可以对来自同一个表的两个查询使用JOIN,还是应该使用其他内容?

2 个答案:

答案 0 :(得分:3)

我猜测channel_oid, oid是候选键。在最简单的形式中,您可以加入两个查询,如(未经测试):

SELECT A._id, A.now_oid, ..., B.title, ...
FROM (
    SELECT now.channel_oid,
        now.oid,
        now.title,
        now.start_time,
        now.end_time,
    FROM epg_event now
    WHERE  now.start_time <= datetime('now') AND now.end_time > datetime('now')
) AS A
JOIN (
    SELECT next.channel_oid,
        next.oid,
        next.title,
        MIN(next.start_time) as start_time,
        next.end_time 
    FROM epg_event next
    WHERE next.start_time > datetime('now')  
    GROUP BY next.channel_oid
) AS B
    ON A.channel_oid = B.channel_oid
   AND A.oid = B.oid
ORDER BY A.channel_oid

答案 1 :(得分:1)

非常感谢Lennart指出我正确的方向。这需要一些试验和错误,但我现在正在获得我的目标。

SELECT A.channel_oid AS _id, A.oid AS now_oid, A.title AS now_title,
       A.start_time AS now_start_time, A.end_time AS now_end_time,
       B.oid AS next_oid, B.title AS next_title, B.start_time AS next_start_time,
       B.end_time AS next_end_time
FROM (
    SELECT channel_oid,
        oid,
        title,
        start_time,
        end_time
    FROM epg_event
    WHERE  start_time <= datetime('now') AND end_time > datetime('now')
    ORDER BY channel_oid) AS A  
JOIN (
    SELECT channel_oid,
        oid,
        title,
        MIN(start_time) as start_time,
        end_time
    FROM epg_event
    WHERE start_time > datetime('now')  
    GROUP BY channel_oid)  AS B 
ON A.channel_oid = B.channel_oid