[英]Comparison with trailing spaces in MySQL
此 SQL 查詢:
select c1 from table where c1='';
返回 MySQL 中具有c1=' '
(一個空格)的行。
這是故意的還是錯誤?
編輯:請在此處檢查 SQL Fiddle 鏈接, SELECT
查詢中的空格數無關緊要。
這一切都在文檔中說明。 我在這里引用了重要的觀點。 但我建議閱讀完整的文檔
VARCHAR 值在存儲時不會被填充。 根據標准 SQL,在存儲和檢索值時保留尾隨空格。
另一方面,CHAR 值在存儲時會被填充,但在檢索時會忽略尾隨空格。
所有 MySQL 歸類都是 PADSPACE 類型。 這意味着比較 MySQL 中的所有 CHAR、VARCHAR 和 TEXT 值,而不考慮任何尾隨空格。 此上下文中的“比較”不包括 LIKE 模式匹配運算符,對於其尾隨空格很重要。
說明:使用比較運算符 ('=') 比較字符串時,會忽略Trailing spaces
。 但是尾隨空格對於LIKE
( pattern matching operator
)很重要
如果您的列來自CHAR類型而不是 VARCHAR,那么這是正確的。 在 CHAR-Fields 上將忽略比較時的尾隨空白! 所以
field = ''
field = ' '
是相同的。
此行為符合 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'
為假)。
如果c1
是CHAR(1)
,那么這是正確的,因為CHAR
列是固定寬度的,如有必要,將用空格填充。
因此,即使您將''
放入CHAR(1)
字段中,您也會在SELECT
得到' '
。 此外,過濾空字符串將產生' '
。
請接受馬丁史密斯的回答,因為他在我面前給出了正確的提示。
此外,根據
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)
嘗試這個 -
Select case when c1 = '' then ' ' else c1 end from table ;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.