为什么文本值不等于字符值?
Why text value is not equal to char value?
我正在翻阅一本关于 PostgreSQL 的书并找到以下示例:
SELECT
'a '::VARCHAR(2) = 'a '::TEXT AS "Text and varchar",
'a '::CHAR(2) = 'a '::TEXT AS "Char and text",
'a '::CHAR(2) = 'a '::VARCHAR(2) AS "Char and varchar";
产生:
这很奇怪,书中说:
The preceding example shows that 'a '::CHAR(2) equals 'a
'::VARCHAR(2), but both have different lengths, which isn't logical.
Also, it shows that 'a'::CHAR(2) isn't equal to 'a '::text. Finally,
'a '::VARCHAR(2) equals 'a'::text. The preceding example causes
confusion because if variable a is equal to b, and b is equal to
c, a should be equal to c according to mathematics.
但是没有解释为什么?是否有关于数据存储方式的问题,或者这可能是 CHAR
类型的一些遗留行为?
您看到的行为似乎是因为 Postgres 在幕后进行了一些转换。请考虑以下稍作修改的查询版本:
SELECT
'a '::VARCHAR(2) = 'a '::TEXT AS "Text and varchar",
'a '::CHAR(2) = CAST('a '::TEXT AS CHAR(2)) AS "Char and text",
'a '::CHAR(2) = 'a '::VARCHAR(2) AS "Char and varchar";
这returns True
用于所有三个比较。显然 Postgres 正在将第二次比较的双方都投射到 text
,而 a[ ]
([ ]
表示 space)与 CHAR(2)
不是同一回事来自 text
.
回想一下,为了在 SQL 数据库中进行 A = B
比较,A
和 B
的两种类型必须相同。如果不是,即使看起来相等比较是独立工作的,但在幕后很可能会发生隐式转换。
我正在翻阅一本关于 PostgreSQL 的书并找到以下示例:
SELECT
'a '::VARCHAR(2) = 'a '::TEXT AS "Text and varchar",
'a '::CHAR(2) = 'a '::TEXT AS "Char and text",
'a '::CHAR(2) = 'a '::VARCHAR(2) AS "Char and varchar";
产生:
这很奇怪,书中说:
The preceding example shows that 'a '::CHAR(2) equals 'a '::VARCHAR(2), but both have different lengths, which isn't logical. Also, it shows that 'a'::CHAR(2) isn't equal to 'a '::text. Finally, 'a '::VARCHAR(2) equals 'a'::text. The preceding example causes confusion because if variable a is equal to b, and b is equal to c, a should be equal to c according to mathematics.
但是没有解释为什么?是否有关于数据存储方式的问题,或者这可能是 CHAR
类型的一些遗留行为?
您看到的行为似乎是因为 Postgres 在幕后进行了一些转换。请考虑以下稍作修改的查询版本:
SELECT
'a '::VARCHAR(2) = 'a '::TEXT AS "Text and varchar",
'a '::CHAR(2) = CAST('a '::TEXT AS CHAR(2)) AS "Char and text",
'a '::CHAR(2) = 'a '::VARCHAR(2) AS "Char and varchar";
这returns True
用于所有三个比较。显然 Postgres 正在将第二次比较的双方都投射到 text
,而 a[ ]
([ ]
表示 space)与 CHAR(2)
不是同一回事来自 text
.
回想一下,为了在 SQL 数据库中进行 A = B
比较,A
和 B
的两种类型必须相同。如果不是,即使看起来相等比较是独立工作的,但在幕后很可能会发生隐式转换。