MySQL Conditional

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
User avatar
psurrena
Forum Contributor
Posts: 355
Joined: Thu Nov 10, 2005 12:31 pm
Location: Broolyn, NY

MySQL Conditional

Post 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
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: MySQL Conditional

Post by AbraCadaver »

What do you mean "optional"? If you remove the condition altogether then it will be optional.
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
User avatar
psurrena
Forum Contributor
Posts: 355
Joined: Thu Nov 10, 2005 12:31 pm
Location: Broolyn, NY

Re: MySQL Conditional

Post by psurrena »

Code: Select all

project_order.category_id = $id
may not exist...
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: MySQL Conditional

Post 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.
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply