简体   繁体   English

WHERE子句中的条件检查

[英]Conditions check in WHERE clause

I am trying to build a query and this is its WHERE clause so far: 我正在尝试建立一个查询,到目前为止,这是它的WHERE子句:

WHERE ( s.subject_name LIKE '%$keyword%' OR
        c.city_name LIKE '%$keyword%' OR
        o.option_name LIKE '%$option%' OR
        d.district_id = $districtId OR
        c.city_id = $cityId
       )

My actual conditions are: 我的实际情况是:

  • $keyword should always hold a value. $keyword应该始终包含一个值。 Other 3 may not. 其他3个可能不行。
  • If only $keyword has a value, returned records should match $keyword in subject_name or city_name . 如果只有$keyword具有值,则返回的记录应与subject_namecity_name中的$keyword匹配。
  • If $optional have a value, then returned records should match $keyword and $option 如果$optional有一个值,则返回的记录应匹配$keyword$option
  • If $districtId has a value, then results should match the 3 variable values ( $keyword , $option , $districtId ) 如果$districtId有一个值,则结果应匹配3个变量值( $keyword$option$districtId
  • Finally if $cityId has a value along with the other 3, returned result should match all 4 variables' values. 最后,如果$cityId具有一个值以及其他3个值,则返回的结果应匹配所有4个变量的值。

These conditions come from my search page. 这些条件来自我的搜索页面。 $keyword is the value from a text box and a keyword is required to start searching. $keyword是文本框中的值,并且需要关键字才能开始搜索。 That's why I said it always has a value. 这就是为什么我说它总是有价值。 Other 3 values come from select boxes that allows to select the items when they are needed. 其他3个值来自选择框,该框允许在需要时选择项目。

I tried to make the query, its ok. 我试图进行查询,确定。 But I am really confused with the WHERE clause. 但是我真的对WHERE子句感到困惑。 Above code is from my WHERE clause so far. 到目前为止,以上代码来自我的WHERE子句。 But I can not get my desired result. 但是我无法获得理想的结果。

If you want to achieve this in pure SQL, this is what you need (or at least it should be close enough): 如果要在纯SQL中实现此目标,则需要此(或者至少应该足够接近):

WHERE (
    ( s.subject_name LIKE '%$keyword%' OR c.city_name LIKE '%$keyword%' )
    AND ('$option' = '' OR (
        o.option_name LIKE '%$option%' AND (
            '$districtId' = '' OR (
                d.district_id = $districtId AND (
                    '$cityId' = '' OR c.city_id = $cityId
                )
            )
        )
    )
)

However, this is by far sub-optimal. 但是,这到目前为止不是最佳的。 Instead, you should check the contents of user input in PHP and run a different query depending on this input. 相反,您应该检查PHP中用户输入的内容,并根据此输入运行其他查询。 You could also build the query dynamically: 您还可以动态构建查询:

$query = "SELECT ...";

$query .=
    " WHERE ( ( s.subject_name LIKE '%$keyword%' OR c.city_name LIKE %$keyword%' )";
if ( !empty($option) ) {
    $query .= " AND o.option_name LIKE '%$option%'";
    if ( !empty($districtId) ) {
        $query .= " AND d.district_id = $districtId";
            if ( !empty($cityId) ) {
                $query .= " AND c.city_id = $cityId";
            }
    }
}
$query .= ')';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM