使用 MySQL 检查空字段

我已经写了一个查询,以检查用户与某些标准,其中之一是他们有一个电子邮件地址。

我们的网站将允许用户有或没有电子邮件地址。

$aUsers=$this->readToArray('
SELECT `userID`
FROM `users`
WHERE `userID`
IN(SELECT `userID`
FROM `users_indvSettings`
WHERE `indvSettingID`=5 AND `optionID`='.$time.')
AND `email`!=""
');

这是在 SQL 中检查空字段的最佳方法吗?我刚刚尝试了“ IS NOT NULL”,这仍然返回一个用户记录,没有他们有一个电子邮件地址。

上面的查询很有用,但出于好奇,我想知道我的方法是否正确。

191303 次浏览

Yes, what you are doing is correct. You are checking to make sure the email field is not an empty string. NULL means the data is missing. An empty string "" is a blank string with the length of 0.

You can add the null check also

AND (email != "" OR email IS NOT NULL)

An empty field can be either an empty string or a NULL.

To handle both, use:

email > ''

which can benefit from the range access if you have lots of empty email record (both types) in your table.

There's a difference between an empty string (email != "") and NULL. NULL is null and an Empty string is something.

This will work but there is still the possibility of a null record being returned. Though you may be setting the email address to a string of length zero when you insert the record, you may still want to handle the case of a NULL email address getting into the system somehow.

     $aUsers=$this->readToArray('
SELECT `userID`
FROM `users`
WHERE `userID`
IN(SELECT `userID`
FROM `users_indvSettings`
WHERE `indvSettingID`=5 AND `optionID`='.$time.')
AND `email` != "" AND `email` IS NOT NULL
');

If you want to find all records that are not NULL, and either empty or have any number of spaces, this will work:

LIKE '%\ '

Make sure that there's a space after the backslash. More info here: http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html

You could use

IFNULL(email, '') > ''

check this code for the problem:

$sql = "SELECT * FROM tablename WHERE condition";


$res = mysql_query($sql);


while ($row = mysql_fetch_assoc($res)) {


foreach($row as $key => $field) {


echo "<br>";


if(empty($row[$key])){


echo $key." : empty field :"."<br>";


}else{


echo $key." =" . $field."<br>";


}
}
}