views:

148

answers:

1

What am I doing wrong with this:

$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";

The first statement before the UNION works well on its own, but this one above returns:

mysql_fetch_array() warning - supplied argument is not a valid MySQL result resource

Am I right in believing that UNION will not return duplicate entries, in which case the second SELECT statement doesn't need to have the NOT LIKE but will just return everything that wasn't listed in the first statement.

+2  A: 

EDIT: This query should get you the rows matched by filter first, followed by those not matched:

SELECT *
FROM content
ORDER BY
  CASE WHEN threadName LIKE '%$filter%' THEN 0 ELSE 1 END,
  lastUpdated DESC

Note that you should never SELECT *, list the necessary columns instead.

Peter Lang
It sounds like he wants all matches to appear first, ordered by lastUpdate, then all non-matches. So the ORDER BY would have to be on a CASE statement against (threadname LIKE '%$filter%'), then lastUpdated.
LesterDove
I think you may have a point with the ORDER BY. What I'm really trying to do is to have all those results that were actually searched for ($filter) at the top and the rest beneath them so an ORDER BY at the end might change this surely?
kalpaitch
And yes someone pointed out not to use SELECT * before, thanks, I will change that eventually
kalpaitch
@LesterDove, kalpaitch: Thanks, my edited query should take care of that.
Peter Lang
Cheers again. Aside from query speed what are the reasons for not using *. And what is the realy speed difference, have you seen any results?
kalpaitch
@kalpaitch: Unless you only select columns that are part of an index, the speed difference will not really matter. By listing all columns you make reading the query easier (for humans) and it gets much easier to find out what columns are used by which queries. You are going to appreciate that once you try to modify/drop/rename a column :)
Peter Lang