3

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.

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1
(SELECT *
FROM   content
WHERE  threadName LIKE '%$filter%')
UNION
(SELECT *
FROM   content
WHERE  threadName NOT LIKE '%$filter%')
ORDER BY lastUpdated desc

Edit: MySQL needs some bracketing and requires to do the order after the union, sorry forgot about that.

1 Comment

I'm afraid to joy with this as yet, have a look at my updated code above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.