使用UNION将两个语句与LIMITS结合使用

时间:2012-05-30 08:48:21

标签: sql sqlite

有没有办法将这两个语句组合成一个而没有重复的条目?

SELECT * FROM Seq where JULIANDAY('2012-05-25 19:02:00')<=JULIANDAY(TimeP) 
         order by TimeP limit 50

SELECT * FROM Seq where JULIANDAY('2012-05-29 06:20:50')<=JULIANDAY(TimeI)  
         order by TimeI limit 50

SQLITE不支持我的第一个显而易见的尝试(语法错误:在UNION之前不应出现限制子句):

SELECT * FROM Seq where JULIANDAY('2012-05-25 19:02:00')<=JULIANDAY(TimeP) 
         order by TimeP limit 50
UNION
SELECT * FROM Seq where JULIANDAY('2012-05-29 06:20:50')<=JULIANDAY(TimeI)
         order by TimeI limit 50

3 个答案:

答案 0 :(得分:26)

使用子查询并在其中执行限制。

SELECT  *
FROM    (   SELECT  * 
            FROM    Seq 
            WHERE   JULIANDAY('2012-05-25 19:02:00') <= JULIANDAY(TimeP) 
            ORDER BY TimeP
            LIMIT 50
        )
UNION
SELECT  *
FROM    (   SELECT  * 
            FROM    Seq 
            WHERE   JULIANDAY('2012-05-29 06:20:50') <= JULIANDAY(TimeI) 
            ORDER BY TimeI
            LIMIT 50
        )

答案 1 :(得分:7)

分阶段处理查询:

  1. FROM子句和所有连接;
  2. WHERE子句和所有谓词。因此,如果您想在结果集中看到NULL值,则不应在OUTER部分中过滤WHERE - 已加入的表列,因为这会将您的查询转换为{{1}加入;
  3. INNERGROUP BY条款;
  4. 查询组合:HAVINGUNIONINTERSECTEXCEPT
  5. MINUS
  6. ORDER BY
  7. 因此,正如其他人所指出的那样,在 LIMIT子句之前使用ORDER BYLIMIT 是合理的错误。您应该使用子查询:

    UNION

答案 2 :(得分:2)

           SELECT * from 
           (SELECT * 
           FROM Seq 
           where JULIANDAY('2012-05-25 19:02:00')<=JULIANDAY(TimeP) 
           order by TimeP limit 50)
           UNION
           SELECT * from 
           (SELECT * 
           FROM Seq 
           where JULIANDAY('2012-05-29 06:20:50')<=JULIANDAY(TimeI)
           order by TimeI limit 50)

这应该可以解决问题