简体   繁体   中英

SQL query returns wrong results

I have one column in my table named 'process' which is a BOOLEAN type and has a value NULL by default. When I set the values of 'process' of all rows to NULL and do the query

SELECT * FROM `tablename` WHERE `process` != 1

MySQL returns an empty result set. I also get the same result when I do

SELECT * FROM `tablename` WHERE `process` = NULL

Furthermore, when I use PHP to print out the rows like

$result = mysqli_query($conn, "SELECT * FROM log");
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
    if ($row['process'] != 1)
        echo $row['time']." ".$row['event']."\n";
}

I don't get an empty result set. Can anyone explain to me where the problem is?

Thanks.

When you fire the SQL:

SELECT * FROM `tablename` WHERE `process` != 1

The result set is returned empty because this will look for the records which do not have value '1'. NULL is not a value

SELECT * FROM `tablename` WHERE `process` = NULL

This sounds completely wrong, As I have informed 'NULL' is not a value. Off couse, this is the wrong method you're trying to apply.

In nutshell, NULL is not a value, therefore it cannot equal = or not equal != anything. It is not the same as zero 0 which is a value.

Check the like for better understand.

Hope this help you!

To get Record which has NULL value,

you should Use isnull() instead of column=NULL

SELECT * FROM `tablename` WHERE ISNULL(`process`);

您可以使用IS NULL

SELECT * FROM tablename WHERE process IS NULL

If you are defining logical false as the boolean column being not equal to 1 (meaning 0 or NULL ), then you should use this logic:

SELECT *
FROM tablename
WHERE process <> 1 OR process IS NULL;

You could also slightly consolidate the WHERE clause using COALESCE :

SELECT *
FROM tablename
WHERE COALESCE(process, 0) <> 1;

Null is not a Value a column can have. Its more like a state, therefor you need to write

SELECT * FROM `tablename` WHERE `process` IS NULL

Also you can't reverse a clause with !=, you need to use <> in that case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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