Where IF条款中的MySQL IF条件

时间:2011-11-23 13:23:30

标签: mysql if-statement where-clause

是否有可能通过IF条件决定哪个条款我想选择。

类似的东西:

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

任何人都有一个Snippet或者其他东西给我?

先谢谢 真糟糕

3 个答案:

答案 0 :(得分:8)

在这种情况下,您仍然可以使用相当常见的WHERE语句编写,例如:

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

当然,您应该在适当的条件下替换WHERECLAUSE1WHERECLAUSE2

答案 1 :(得分:5)

很简单,你应该阅读Boolean Algebra。在你的情况下,我们走了:

A = WhereClause1
B = WhereClause2
X = Choice

您需要选择X && A OR行与!X && B的行。所以基本上你的表达式是:(X && A) || (!X && B)。这导致:

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

答案 2 :(得分:0)

$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.';
}