Skip to content
Advertisement

Combine two statements with LIMITS using UNION

Is there a way to combine these two statements into one without having duplicate entries?

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

My first, obvious attempt is not supported by SQLITE (Syntax error: Limit clause should come after UNION not before):

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

Advertisement

Answer

Use subqueries and perform the limit within them.

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
        )
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement