MySQL 当 a = 0, b = 0, 但 a <> b (二进制)

Eva*_*oll 5 mysql datatypes bitwise-comparison

知道为什么会这样,

CREATE TABLE f AS
  SELECT b'000000001' AS a, x'01' AS b;
Run Code Online (Sandbox Code Playgroud)

这将创建两列

`a` varbinary(2) NOT NULL,
`b` varbinary(1) NOT NULL
Run Code Online (Sandbox Code Playgroud)

然而,当我跑步时,

SELECT a=0, b=0, a=b, a<>b FROM f;
+-----+-----+-----+------+
| a=0 | b=0 | a=b | a<>b |
+-----+-----+-----+------+
|   1 |   1 |   0 |    1 |
+-----+-----+-----+------+
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?从关于BINARY 和 VARBINARY 类型文档,

所有字节在比较中都很重要,包括ORDER BYDISTINCT操作。 0x00字节和空格在比较中是不同的,使用0x00 < space.

这解释了为什么a<>b,但为什么a=0,或b=0那里?

Ric*_*mes 8

BINARY is a misnomer. It really refers to a string of bytes; it does not refer to binary numbers, and it isn't a unique datatype.

Also, = and <> adapt to the datatype(s) involved:

SELECT a=0, b=0,    -- numeric comparisons
       a=b, a<>b    -- BLOB comparisons; length matters
    FROM f;
Run Code Online (Sandbox Code Playgroud)

It is a combination of the Operator and the Datatypes that controls what string vs numeric operations.

Some info on datatypes:

BINARY / VARBINARY / BLOB can be manipulated with "bit" operators | & ~ ^ -- not to be confused with logical operators AND (&&) and OR (||). BLOB-like columns are used for non-character strings, such as images. MySQL 8.0 stretches these operators beyond a 64-bit limit. INT can also be manipulated with bit operators.

The BIT(m) datatype is prefixed with leading zeros if needed to fill out to full byte(s). (Limit 64 bits.) This datatype is almost never used.

BINARY(1) and BINARY(22) are 1- and 22-byte datatypes. CAST(1 AS BINARY(1) converts the first 1 to a string "1", then stuffs in hex 31 (ascii code for "1"). Try SELECT HEX(CAST(1 AS binary(1))), HEX(CAST("1" AS BINARY(1))); -- both yield 31.