简体   繁体   English

如何在SQL的WHERE子句中用通配符char替换空变量

[英]How to replace empty variable with the wildcard char in WHERE clause in sql

Im passing two variables, via ajax - post method, into WHERE statement in query. 我通过ajax-post方法将两个变量传递给查询中的WHERE语句。 Second variable $var2 is optional and it may or may not be sent. 第二个变量$ var2是可选的,可以发送也可以不发送。 That means that second variable can be empty and query would not return any result. 这意味着第二个变量可以为空,查询将不返回任何结果。

SELECT table1.*
        FROM table1
        LEFT OUTER JOIN table2 ON table1.table2_id = table2.id 
        WHERE table2.field1 = '".$var1."' AND table2.field2 = '".$var2."'
        ORDER BY table2.counter DESC
        LIMIT 10;

My first thought was to write if statement, something like 我的第一个想法是编写if语句,例如

if(empty($var2)){
   query = ....WHERE table2.field1 = '".$var1."'...
}else{
   WHERE table2.field1 = '".$var1."' AND table2.field2 = '".$var2."'
}

Second thought was to assign * wildcard to $var2 if it is empty(this is not working). 第二个想法是,如果$ var2为空,则将*通配符分配给$ var2(这不起作用)。

Is there better way than if statement that could handle this problem? 有没有比if语句更好的方法可以处理此问题?

Thanks 谢谢

I usually do something like this: 我通常会这样:

$descriptiveName = !empty($var2) ? "AND table2.field2 = '$var2'" : "";

"SELECT table1.*
FROM table1
LEFT OUTER JOIN table2 ON table1.table2_id = table2.id 
WHERE table2.field1 = '$var1'
$descriptiveName
ORDER BY table2.counter DESC
LIMIT 10"

That will set the $descriptiveName variable to a blank string (that will be ignored) if $var2 is empty. 如果$var2为空,这会将$descriptiveName变量设置为空白字符串(将被忽略)。 It is also easy to add more than one condition this way, but if there are too many it is usually better to have two separate queries. 以这种方式添加多个条件也很容易,但是如果数量太多,通常最好有两个单独的查询。

This approach is correct; 这种方法是正确的。

if(empty($var2)){
   query = ....WHERE table2.field1 = '".$var1."'...
}else{
   WHERE table2.field1 = '".$var1."' AND table2.field2 = '".$var2."'
}

Add or take away from the query depending on the arguments. 根据参数添加或删除查询。 I do not think there is a wildcard like you want. 我认为没有想要的通配符。 Even if there was it doesn't matter, as omitting the second statement using an if has the same effect. 即使有关系也没关系,因为使用if省略第二条语句具有相同的效果。

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

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