WHERE a OR b IN (x) 不匹配,但 returns 行

WHERE a OR b IN (x) does not match, but returns rows

我的 table 看起来像这样:

| a  | ts_9 | ts_11 |
|----|------|-------|
| yx | 0    |       |
| xy | 0    |       |

并且出于某种原因,当我调用时返回行:

SELECT * FROM things WHERE ts_9 IN ("asdewdwedewd") OR ts_11 IN ("asdewdwedewd")

为什么会这样?

随时使用复制粘贴在您的数据库中重新创建它:

CREATE TABLE `things` (
  `a` char(12) NOT NULL DEFAULT '',
  `ts_9` decimal(2,0) NOT NULL,
  `ts_11` char(1) NOT NULL DEFAULT '',
  PRIMARY KEY (`a`),
  UNIQUE KEY `a` (`a`) );

INSERT INTO `things` (`a`, `ts_9`, `ts_11`) VALUES ('yx', '0', ''), ('xy', '0', '');

优化器将数据归为同一类型。 将字符串转换为十进制时,我们得到零。 需要预定义或转换数据类型。

因为 ts_9 IN ("asdewdwedewd") 评估为真。更具体地说,ts_9 的值为整数 0。根据 documentation

If all values are constants, they are evaluated according to the type of expr

换句话说,"asdewdwedewd" 将被视为一个整数。当 mysql 将其转换为 int cast("asdewdwedewd" as signed integer) 时,我们得到 0。因此 0 in (0) 计算结果为真。