Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two mysql query into one

What is the proper 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 "Incorrect usage of UNION and ORDER BY".

EDIT Additionally, I want the result to be returned in a single row. So that I can access the value in php eg

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

From Simon's suggestion, I should not use UNION because I want to return a single row of data

like image 403
PutraKg Avatar asked Jan 11 '13 15:01

PutraKg


People also ask

How run multiple MySQL queries?

Multiple statements or multi queries must be executed with mysqli::multi_query(). The individual statements of the statement string are separated by semicolon. Then, all result sets returned by the executed statements must be fetched.


1 Answers

You can't ORDER BY in your first SELECT and then UNION it.

Edit
You can however

apply ORDER BY or LIMIT to an individual SELECT, place the clause inside the parentheses that enclose the 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);

Which then makes your SQL

(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 in an 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;
like image 56
Simon Martin Avatar answered Sep 26 '22 09:09

Simon Martin