与MySQL中的尾随空格比较

eqoofvh9  于 2023-02-18  发布在  Mysql
关注(0)|答案(7)|浏览(146)

此SQL查询:

select c1 from table where c1='';

返回MySQL中包含c1=' '(一个空格)的行。
这是有意的还是错误?
EDIT:请检查这里的SQL Fiddle链接,SELECT查询中的空格数无关紧要。

fnatzsnv

fnatzsnv1#

这些都在文档中说明了。我在这里引用了要点。但是我建议浏览完整的documentation
VARCHAR值在存储时不填充。在存储和检索值时保留尾随空格,这与标准SQL一致。
另一方面,CHAR值在存储时会被填充,但在检索时会忽略尾随空格。

所有MySQL归类的类型都是PADSPACE。这意味着MySQL中的所有CHAR、VARCHAR和TEXT值都将进行比较,而不考虑任何尾随空格。本文中的“比较”不包括LIKE模式匹配运算符,尾随空格对该运算符很重要。

**说明:**使用比较运算符('=')比较字符串时,将忽略Trailing spaces。但尾随空格对于LIKEpattern matching operator)很重要

vx6bjr1n

vx6bjr1n2#

这是记录在案的行为。
LIKE的MySQL文档提到
尾随空格是有效的,**对于使用=运算符执行的CHAR或VARCHAR比较,**不是有效的
SQL Server works the same way.

lyfkaqu1

lyfkaqu13#

如果你的列是来自类型CHAR而不是VARCHAR,那么这是正确的。在CHAR-Fields上,在比较时将忽略尾随空格!所以

field = ''
field = '    '

都是一样的。

dfddblmv

dfddblmv4#

此行为符合ANSI SQL-92标准。任何符合此标准的数据库都将表现出相同的行为。

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.

因此,根据这些规范,'abc' = 'abc ''' = ' '的值为真(但'' = '\t'为假)。

wb1gzix0

wb1gzix05#

如果c1CHAR(1),则这是正确的,因为CHAR列是固定宽度,必要时将填充空白。
因此,即使你把''放入CHAR(1)字段,你也会在SELECT ing之后得到' '。同样,过滤一个空字符串也会得到' '

请接受马丁·史密斯的回答,因为他在我面前给出了正确的提示

此外,根据MySQL文档,在将字符串与=进行比较时,将忽略尾随空格,因此,如果c1列仅包含空格(或者在您的情况下包含一个空格),则即使您过滤WHERE c1 = '',也会返回该空格:
特别是,尾部空格很重要,而对于使用=运算符执行的CHAR或VARCHAR比较则不是这样

mysql> SELECT 'a' = 'a ', 'a' LIKE 'a ';
+------------+---------------+
| 'a' = 'a ' | 'a' LIKE 'a ' |
+------------+---------------+
|          1 |             0 |
+------------+---------------+
1 row in set (0.00 sec)
dwthyt8l

dwthyt8l6#

从表t_name group by l中选择c1,长度(c1)为l
(数字)

gzszwxb4

gzszwxb47#

试试这个-

Select case when c1 = '' then ' ' else c1 end from table ;

相关问题