Combine two mysql queries into one

What is the correct syntax to combine these two queries?

SELECT clicks FROM clicksTable WHERE clicks > 199 ORDER BY clicks ASC LIMIT 1 

and

 SELECT clicks FROM clicksTable ORDER BY clicks DESC LIMIT 1 

I tried:

 SELECT clicks FROM clicksTable WHERE clicks > 199 ORDER BY clicks ASC LIMIT 1 UNION SELECT clicks FROM clicksTable ORDER BY clicks DESC LIMIT 1; 

but I get "Misuse of UNION and ORDER BY".

EDIT In addition, I want the result to be returned on a single line. So that I can access the value in php like

 $row['nextclick'] and $row['topclick'] 

From Simon’s suggestion I shouldn’t use UNION because I want to return one row of data

+4
source share
3 answers

You cannot ORDER BY in your first SELECT and then UNION .

Edit
However you can

apply ORDER BY or LIMIT to a single SELECT, put the sentence in parentheses that enclose SELECT:

as in the MySQL UNION documentation

 (SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10) UNION (SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10); 

What does your sql do

 (SELECT clicks FROM clicksTable WHERE clicks > 199 ORDER BY clicks ASC LIMIT 1) UNION (SELECT clicks FROM clicksTable ORDER BY clicks DESC LIMIT 1); 

Edit 2
To return to array

 SELECT (SELECT clicks FROM clicksTable WHERE clicks > 199 ORDER BY clicks ASC LIMIT 1) AS NextClick, (SELECT clicks FROM clicksTable ORDER BY clicks DESC LIMIT 1) AS TopClick; 
+10
source
 SELECT clicks FROM (SELECT clicks FROM clicksTable WHERE clicks > 199 ORDER BY clicks ASC LIMIT 1) A UNION SELECT clicks FROM (SELECT clicks FROM clicksTable ORDER BY clicks DESC LIMIT 1) B; 
+3
source

First, do you want union or union all ?

The problem is order by in the first part. You can fix this using subqueries:

 (select * from (SELECT clicks FROM clicksTable WHERE clicks > 199 ORDER BY clicks ASC LIMIT 1)) UNION ALL (select * from (SELECT clicks FROM clicksTable ORDER BY clicks DESC LIMIT 1)) 

In an expression, union order by permitted only at the end and applies to the entire expression.

+1
source

All Articles