1. 程式人生 > 其它 >MySQL語法介紹——like和=的區別

MySQL語法介紹——like和=的區別

技術標籤:MySQLmysqlsql

MySQL中’like’和’='用於查詢的區別

MySQL中用於查詢的關鍵字中’like’稱為模糊查詢,’='就是判斷是否相等,但使用時出現了一個小問題。

問題描述

這裡我需要對錶格最後結果中的’department_name’屬性進行精確查詢值為’IT’的記錄。

話不多說,先上程式碼

SELECT 
  d.`department_id`,
  d.`department_name`,
  e.`employee_id`,
  e.`last_name` 
FROM
  departments d 
  LEFT OUTER JOIN employees e 
    ON d.`department_id` = e.`department_id` 
WHERE d.`department_name` LIKE 'IT' ;

注意,這裡,最後一條查詢語句使用的是’like’關鍵字,
結果如下,共有5條查詢結果
在這裡插入圖片描述

再來看一下’='的查詢結果,先上程式碼

SELECT 
  d.`department_id`,
  d.`department_name`,
  e.`employee_id`,
  e.`last_name` 
FROM
  departments d 
  LEFT OUTER JOIN employees e 
    ON d.`department_id` = e.`department_id` 
WHERE d.`department_name` = 'IT' ;

相比於使用‘like’的程式碼,這裡只有最後一條查詢語句中將’like’改為了’=’。我們看一下結果,共有7條語句

在這裡插入圖片描述
相比於’like’關鍵字,‘=’竟然多查出了兩條記錄,我們知道,like是模糊查詢,按照道理應該包含’='的結果,為什麼反而少了2條結果呢?


解釋:

1)
直接跳進原表,我們發現在department_id為210和230的兩條記錄中,department_name的值其實是’IT ‘。也就是後面多了一個空格。
如下圖:
在這裡插入圖片描述
問題來了,即使是這樣為什麼’=‘能查詢出來,而’like’就不可以呢?
2)
因為在’='的查詢中會忽略空格,也就是說即使在上面的程式碼中我將語句改為 = 'IT ',其結果也仍然是7條記錄;而like的查詢中是考慮空格的,將會嚴格的進行比較,如果將語句改為 like 'IT ',那麼結果將是上一次查詢被忽略掉的2條記錄。

結論:

當我們進行精確查詢時,最好不要使用’like’,該使用’=‘的就使用’=’,真的非要使用’like’那麼就記住’like’和
'='在處理空格方面的不同吧。


附:
翻閱官網文件,可以看到

MySQL collations have a pad attribute of PAD SPACE.
PAD SPACE collations treat trailing spaces as insignificant in comparisons; strings are compared without regard to trailing spaces. The server SQL mode has no effect on comparison behavior with respect to trailing spaces.

For those cases where trailing pad characters are stripped or comparisons ignore them, if a column has an index that requires unique values, inserting into the column values that differ only in number of trailing pad characters results in a duplicate-key error. For example, if a table contains ‘a’, an attempt to store 'a ’ causes a duplicate-key error.

對於MySQL來說,String型別的值的尾部的空格在比較時是被忽略不計的,如果你先儲存一個’a’,然後想修改為’a ',將會報錯衝突。

官網參考文件地址