简体   繁体   中英

false OR false = true in MySQL? Very odd behaviour

Basically, my 0 OR 0 is returning 1 - that's not really what I wanted :) I'm not really sure why because if I select 0 OR 0 I get 0..

I think this could be because is_premium_dealer is an enum('0','1') rather than a bool (don't ask me why, I didn't design this database!)

Does anyone know if this is because of the ENUM, and if so how I'd cast it to an integer?

Thanks in advance! John.

SELECT is_premium_dealer, company_name,
(SELECT COUNT(*) FROM adverts WHERE user_id = users.id AND is_archived = 0) AS innerquery,
((SELECT COUNT(*) FROM adverts WHERE user_id = users.id AND is_archived = 0 AND is_deleted = 0) > 0 OR is_premium_dealer = 1) AS logicissue
FROM `user_profiles_dealers` 
LEFT JOIN `users` ON user_profiles_dealers.user_id = users.id 
LEFT JOIN `counties` ON user_profiles_dealers.county_id = counties.id 
LEFT JOIN `countries` ON user_profiles_dealers.country_id = countries.id 
WHERE (users.is_active=1) 
AND (((SELECT COUNT(*) FROM adverts WHERE user_id = users.id AND is_archived = 0 AND     is_deleted = 0) > 0) OR is_premium_dealer > 0) 
AND company_name like '%autocraft%' limit 5\G

The result:

*************************** 1. row ***************************
is_premium_dealer: 0
company_name: A Company
innerquery: 0
logicissue: 1
1 row in set (0.00 sec)

答案是将is_premium_dealer包装在BINARY()函数中,该函数似乎将字符串或任何内容转换为可以按预期计算的二进制值。

That is because is_premium_dealer = 1 filters records by ENUM index . From the documentation - ENUM values are represented internally as integers .

The ENUM Type .

Suppose we have - enum_column ENUM('dog', 'cat', 'snake') then:

  • WHERE enum_column = 1 will show records where enum_column = 'dog'
  • WHERE enum_column = 2 will show records where enum_column = 'cat'
  • and so on...

So, you can use number in WHERE condition and without BINARY function, just specify correct enum index.

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