Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort mysql query by filtered query

Tags:

join

mysql

filter

I have two mysql queries:

$sql = "SELECT * FROM content WHERE threadName LIKE '%$filter%' ORDER BY lastUpdated desc";

and

$sql = "SELECT * FROM content ORDER BY lastUpdated desc";

The end result is to have all rows returned from a particular table 'content' but have those that match the variable $filter at the top. Is there either a single query that could combine these two or should I be using a JOIN?

............still to no luck. This is what I currently have:

$sql = "SELECT * FROM content WHERE threadName LIKE '%$filter%' ORDER BY lastUpdated desc UNION SELECT * FROM content WHERE threadName NOT LIKE '%$filter%' ORDER BY lastUpdated desc";

which gives:

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/andrew/public_html/PHP/threadDisplay.php  on line 20

although the first part (before the UNION) works when used on its own.

like image 963
kalpaitch Avatar asked Mar 13 '26 13:03

kalpaitch


1 Answers

How about using a CASE STATEMENT.

Something like

SELECT  * 
FROM    content 
ORDER BY CASE 
            WHEN threadName LIKE '%$filter%' THEN 0
            ELSE 1
        END ASC,
        lastUpdated desc
like image 180
Adriaan Stander Avatar answered Mar 16 '26 04:03

Adriaan Stander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!