Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

mysql - How to string-compare for a single space

I want to check whether a column has any values that are a single space character.

I initially thought that

WHERE my_column = ' '

would be sensible. But no. That will also match columns which have multiple spaces for some reason:

SELECT '    ' = ' '           => true

So I can use a regular express or hex encoding to test:

WHERE HEX(my_column) = '20'
WHERE my_column REGEXP '^ $'

Both work. But I suspect both (certainly the latter) will be quite inefficient.

Is there a better way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A BINARY comparison of the two strings is required for an exact match

Under normal circumstances, trailing whitespace is not regarded in the comparison, but the BINARY operator forces it to be:

BINARY also causes trailing spaces to be significant.

mysql> SELECT BINARY '   ' = ' ';
+--------------------+
| BINARY '   ' = ' ' |
+--------------------+
|                  0 |
+--------------------+

Incidentally, it isn't just whitespace-only comparisons that are affected by the trailing whitespace issue:

mysql> SELECT 'abc   ' = 'abc';
+------------------+
| 'abc   ' = 'abc' |
+------------------+
|                1 |
+------------------+

...but...

mysql> SELECT BINARY 'abc   ' = 'abc';
+-------------------------+
| BINARY 'abc   ' = 'abc' |
+-------------------------+
|                       0 |
+-------------------------+

...and even more confusingly, leading whitespace is significant:

mysql> SELECT ' abc   ' = 'abc';
+-------------------+
| ' abc   ' = 'abc' |
+-------------------+
|                 0 |
+-------------------+

Regarding indexing:

BINARY will prevent an index from being used on the character column. However, a note on the docs suggests that the index will be used if the BINARY operator is applied to the string literal side of the comparison as in:

SELECT * FROM `tbl` WHERE `col` = BINARY 'string   '

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...