在我继承的数据库中,有时二进制问题被编码为("is",“否”),有时被编码为(1,0)。我错误地查询了数字编码字段上的字符串“Yes”。我的猜测是该字符串被 MySQL 变成了“0”。
我有一个这样的查询:
SELECT `children_under_18`
FROM `households`
WHERE `children_under_18` = 'Yes'
GROUP BY `children_under_18`
它最终只匹配 children_under_18
为 0 的记录,这与我想要的相反。我知道我需要更加小心。我正在寻找有关发生的事情的明确答案。
最佳答案
与数字相比,字符串总是转换为0(当然包含数字+字符串的字符串会转换为数字。但这不是一个好的做法)
mysql> SELECT 'Yes' + 0;
+-----------+
| 'Yes' + 0 |
+-----------+
| 0 |
+-----------+
1 row in set, 1 warning (0.00 sec)
mysql> show warnings;
+---------+------+-----------------------------------------+
| Level | Code | Message |
+---------+------+-----------------------------------------+
| Warning | 1292 | Truncated incorrect DOUBLE value: 'Yes' |
+---------+------+-----------------------------------------+
如果你想存储二进制值(是/否或真/假)或小值集,ENUM
是不错的选择。
它占用的磁盘空间很小,并且可以使用有意义的字符串。
mysql> CREATE TABLE enum_test(a ENUM('Yes', 'No'));
Query OK, 0 rows affected (0.00 sec)
mysql> insert into enum_test values('Yes'), ('No'), ('Invalid');
Query OK, 3 rows affected, 1 warning (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 1
mysql> show warnings;
+---------+------+----------------------------------------+
| Level | Code | Message |
+---------+------+----------------------------------------+
| Warning | 1265 | Data truncated for column 'a' at row 3 |
+---------+------+----------------------------------------+
1 row in set (0.00 sec)
mysql> select * from enum_test where a = 'Yes';
+------+
| a |
+------+
| Yes |
+------+
1 row in set (0.00 sec)
mysql> select * from enum_test where a = 'No';
+------+
| a |
+------+
| No |
+------+
1 row in set (0.00 sec)
关于mysql - MySQL整数字段匹配字符串是怎么回事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20110161/