Page 1 of 1

MySQL Conditional

Posted: Tue Mar 30, 2010 10:35 am
by psurrena
Hello!

In the query below, which works, I want the "AND project_order.category_id = $id" part to be optional. How would I go about this?

Code: Select all

SELECT project.id, project.name
FROM project

INNER JOIN project_category ON project_category.project_id = project.id
LEFT JOIN project_order ON project_order.project_id = project.id

WHERE project_category.category_id = $id
AND project_order.category_id = $id

ORDER BY project_order.order ASC

Re: MySQL Conditional

Posted: Tue Mar 30, 2010 10:37 am
by AbraCadaver
What do you mean "optional"? If you remove the condition altogether then it will be optional.

Re: MySQL Conditional

Posted: Tue Mar 30, 2010 10:42 am
by psurrena

Code: Select all

project_order.category_id = $id
may not exist...

Re: MySQL Conditional

Posted: Tue Mar 30, 2010 10:56 am
by AbraCadaver
psurrena wrote:

Code: Select all

project_order.category_id = $id
may not exist...
The field `category_id` may not exist or the variable $id may not exist or the field `category_id` may not have a value in it? If the latter, then:

Code: Select all

WHERE project_category.category_id = $id
AND (project_order.category_id = $id OR project_order.category_id = '')
If it might be null or conatin a zero then use one of those in the condition.