Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two statements with LIMITS using UNION

Tags:

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 
like image 397
nabulke Avatar asked May 30 '12 08:05

nabulke


People also ask

Can we use limit with union in SQL?

Beginning with MySQL 8.0. 19, you can use ORDER BY and LIMIT with TABLE in unions in the same way as just shown, bearing in mind that TABLE does not support a WHERE clause. This kind of ORDER BY cannot use column references that include a table name (that is, names in tbl_name . col_name format).

How do I combine two SQL queries in one result without a UNION?

You need to create two separate queries and join their result not JOIN their tables. Show activity on this post. JOIN and UNION are differents. In your query you have used a CROSS JOIN operation, because when you use a comma between two table you apply a CROSS JOIN.

Can we use WHERE clause with UNION all?

Using the Where Clause With the UNION OperatorWe can use the WHERE clause in either one or both of the SELECT statements to filter out the rows being combined. We can also use the WHERE clause in only one of the SELECT statements in the UNION.


1 Answers

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         ) 
like image 122
GarethD Avatar answered Nov 03 '22 06:11

GarethD