Jings
Jings

Reputation: 8690

MySQL IF Condition in Where Clause

Is it possible to decide by IF Condition which Where Clause I want to choose.

Something like:

IF(DATE_FORMAT(DATE(akDate), '%a')='SAT', USE WHERECLAUSE1, USE WHERECLAUSE2)

Upvotes: 4

Views: 5080

Answers (3)

JackLB
JackLB

Reputation: 110

$query  = " SELECT apt.apt_id,apt.reg_id,apt.u_id,apt.b_id,apt.apt_bathroom,apt.apt_size,apt.apt_rent,apt.apt_desc,apt.negotiable,apt.apt_status,apt.govt_program,building.b_borough,building.b_zipcode,building.b_type,building.b_intersection,building.b_intersection2,building.b_desc FROM apt LEFT JOIN building ON apt.b_id = building.b_id WHERE apt.apt_status = 1 AND ";
if ($search_size != 'empty')
{
    $query .= "apt.apt_size = '".$search_size."' ";
    if ($search_borough != 'empty' || $search_zipcode != 'empty' )
        {
            $query .= " AND ";
        }
}
if ($search_borough != 'empty')
{
    $query .= "building.b_borough= '".$search_borough."' ";
    if ($search_zipcode != 'empty')
        {
            $query .= " AND ";
        }
}
if ($search_zipcode != 'empty')
{
    $query .= "building.b_zipcode = '".$search_zipcode."' ";
}
$query .= "ORDER BY apt.apt_id DESC LIMIT $start,$perpage ";

$query_run = mysql_query ($query);
if (!$query_run)
{
    echo 'Error In the Query limit.';
}

Upvotes: 0

bezmax
bezmax

Reputation: 26122

Easy, you should read on Boolean Algebra. In your case, here we go:

A = WhereClause1
B = WhereClause2
X = Choice

You need to select lines with X && A OR lines with !X && B. So basically your expression will be: (X && A) || (!X && B). Which leads to:

(
    (Choice AND WhereClause1) 
    OR 
    ((NOT Choice) AND WhereClause2)
)

Upvotes: 5

Tadeck
Tadeck

Reputation: 137320

This is the case you can still write using rather common WHERE statement such as this:

... WHERE
(
    (DATE_FORMAT(DATE(akDate), '%a') = 'SAT')
    AND
    (WHERECLAUSE1)
)
OR
(
    (DATE_FORMAT(DATE(akDate), '%a') != 'SAT')
    AND
    (WHERECLAUSE2)
)

where, of course, you should replace WHERECLAUSE1 and WHERECLAUSE2 with appropriate conditions.

Upvotes: 8

Related Questions