3) The comparison of two character strings is determined as fol-
lows:
a) If the length in characters of X is not equal to the length
in characters of Y, then the shorter string is effectively
replaced, for the purposes of comparison, with a copy of
itself that has been extended to the length of the longer
string by concatenation on the right of one or more pad char-
acters, where the pad character is chosen based on CS. If
CS has the NO PAD attribute, then the pad character is an
implementation-dependent character different from any char-
acter in the character set of X and Y that collates less
than any string under CS. Otherwise, the pad character is a
<space>.
b) The result of the comparison of X and Y is given by the col-
lating sequence CS.
mysql> SELECT 'a' = 'a ', 'a' LIKE 'a ';
+------------+---------------+
| 'a' = 'a ' | 'a' LIKE 'a ' |
+------------+---------------+
| 1 | 0 |
+------------+---------------+
1 row in set (0.00 sec)
7条答案
按热度按时间fnatzsnv1#
这些都在文档中说明了。我在这里引用了要点。但是我建议浏览完整的documentation
VARCHAR值在存储时不填充。在存储和检索值时保留尾随空格,这与标准SQL一致。
另一方面,CHAR值在存储时会被填充,但在检索时会忽略尾随空格。
所有MySQL归类的类型都是PADSPACE。这意味着MySQL中的所有CHAR、VARCHAR和TEXT值都将进行比较,而不考虑任何尾随空格。本文中的“比较”不包括LIKE模式匹配运算符,尾随空格对该运算符很重要。
**说明:**使用比较运算符('=')比较字符串时,将忽略
Trailing spaces
。但尾随空格对于LIKE
(pattern matching operator
)很重要vx6bjr1n2#
这是记录在案的行为。
LIKE
的MySQL文档提到尾随空格是有效的,**对于使用=运算符执行的CHAR或VARCHAR比较,**不是有效的
SQL Server works the same way.
lyfkaqu13#
如果你的列是来自类型CHAR而不是VARCHAR,那么这是正确的。在CHAR-Fields上,在比较时将忽略尾随空格!所以
都是一样的。
dfddblmv4#
此行为符合ANSI SQL-92标准。任何符合此标准的数据库都将表现出相同的行为。
因此,根据这些规范,
'abc' = 'abc '
和'' = ' '
的值为真(但'' = '\t'
为假)。wb1gzix05#
如果
c1
是CHAR(1)
,则这是正确的,因为CHAR
列是固定宽度,必要时将填充空白。因此,即使你把
''
放入CHAR(1)
字段,你也会在SELECT
ing之后得到' '
。同样,过滤一个空字符串也会得到' '
。请接受马丁·史密斯的回答,因为他在我面前给出了正确的提示。
此外,根据MySQL文档,在将字符串与
=
进行比较时,将忽略尾随空格,因此,如果c1
列仅包含空格(或者在您的情况下包含一个空格),则即使您过滤WHERE c1 = ''
,也会返回该空格:特别是,尾部空格很重要,而对于使用=运算符执行的CHAR或VARCHAR比较则不是这样
dwthyt8l6#
从表t_name group by l中选择c1,长度(c1)为l
(数字)
gzszwxb47#
试试这个-