MySQL中的替代语法'IS NOT NULL'

时间:2011-07-14 16:00:56

标签: php mysql filter filtering

我正在使用php编译一个很长的mySQL查询。为了上下文,我正在制作一个mySQL查询,用于扫描表'rental',其中包含字段'id','rent','type','num_bedrooms'。条目示例可以是:

rent = 600,type = house,num_bedrooms = 5

rent = 450,type = apartment,num_bedrooms = 3

填写搜索字段时,用户可以选择“任意”搜索“类型”和“num_bedrooms”。注意SQL'类型IS NOT NULL'的行,我的问题是:
可以说'type = NOT NULL'而不是吗? (我的想法是,如果用户搜索'any'代表'type',那么我在php中设置一个变量'$ type'作为'house'找房子,'apartment'找房子,或'NOT NULL '找到所有)

<?php
$min_rent = 200;
$max_rent = 1000;
$type = "NOT NULL"; //or it can be equal to "house" or "apartment" 
$num_bedrooms = 2;  //e.g. 2 or more bedrooms

$sql = "SELECT * FROM properties WHERE ";
$sql .= "rent >= {$min_rent} AND rent <= {$max_rent} AND ";
$sql .= "type = {$type} ";  //in this case, I want 'type' to equal 'NOT NULL'
$sql .= "num_bedrooms >= {$num_bedrooms} ";
?>

我无法测试这个,因为我目前不在我的测试PC上,但我对mySQL语句非常陌生并且想知道这是否可行。感谢

4 个答案:

答案 0 :(得分:3)

实际上有is not NULL的替代方案。例如:

SELECT * FROM properties WHERE type = type

type不为空时,这将返回所有行。

答案 1 :(得分:2)

否 - IS NOT NULL是一项特殊功能。

一般来说,你要做的就是把      $ sql。=“type = {$ type}”;

到if语句中,它将在构造SQL语句时检查$ type的值。

答案 2 :(得分:1)

欢迎来到SO。

SQL以不同于另一个字符串的方式处理null。我不可能说type = "NOT NULL"。 MySQL将返回包含NOT NULL的类型。 (不是,如你所料,那些包含“房子”或“公寓”的人。

该行必须阅读$sql .= "type IS NOT NULL "

当然,您可以在您的特殊情况下添加一个附加上述行的IF语句。

答案 3 :(得分:0)

一种选择是:

SELECT * FROM properties WHERE type != ''