View Full Version : WHERE adn OR query problem

09-15-2011, 08:05 AM
Hello, can anybody help me with this query please.

I have tbl_project that has a row primary `category` which acts as the main decision maker as to what gets selected,
WHERE category LIKE \'%' . $category . '%\'

but it is possible that a row may not have the `category` equaling $category, but it may have a secondary link relationship to the category ( $linkedName = 0 or 1 to determine yes or no relationship) and I would like to include this in the query.
OR \'' . $linkedName . '\' = 1

And that's the part that I'm having trouble with. I think I need to insert the above OR line in after the WHERE line, but it's not giving me a result I desire.
Any help on this would be much appreciated. (I am searching other forums etc but I've not found anything that has helped me yet).

//select projects from database matching chosen category
$query = 'SELECT
\'' . $linkedName . '\',
FROM `tbl_project` `a`, `tbl_projectimages` `b`
WHERE category LIKE \'%' . $category . '%\'

OR \'' . $linkedName . '\' = 1 //this line is giving a confused output, the query works well without this line, but I would like the extra linked results

AND `a`.`projectId` = `b`.`projectId`
AND `selector` = 0
ORDER BY `a`.`projectId` DESC';

Thanks in advance to anybody that looks into my problem.

this question also in weberforums.com

09-15-2011, 12:50 PM
You need to group your WHERE clauses correctly to get the desire result.

$query = "SELECT `a`.`projectId`, `projectName`, `category`, `b`.`imgUrl`, `status`, `alt`, '$linkedName ', `b`.`selector` " .
"FROM `tbl_project` `a`, `tbl_projectimages` `b`" .
"WHERE (category LIKE '%$category%' OR '$linkedName' = 1) " .
"AND `a`.`projectId` = `b`.`projectId` AND `selector` = 0 " .
"ORDER BY `a`.`projectId` DESC';"

Old Pedant
09-15-2011, 05:17 PM
To explain:

First answer this question:

What is the value of 3 + 4 * 2 ?

If you answered 14, go back to school.

Multiplication has higher precedence than addition, so you should multiply 4 * 2 first and then add the 3. The answer is 11. If you *wanted* an answer of 14, you would write

( 3 + 4 ) * 2

Same situation with AND and OR. AND has higher precedence.

So if you write


you have *really* coded

WHERE a OR ( b AND c )
and, DJM pointed out, if you want it the other way you must *explicitly* use parentheses:

WHERE ( a OR b ) AND c