MySQL學習足跡記錄06--數據過濾--LIKE搭配百分號(%)和下劃線(_)通配符 1.LIKE操作符 *%表示匹配任何字符出現任意次數(>=0) 為了便於觀察,先把prod_name字段的所有的數據列出
eg: mysql> SELECT prod_name FROM products; +----------------+ | prod_name | +----------------+ | .5 ton anvil | | 1 ton anvil | | 2 ton anvil | | Detonator | | Bird seed | | Carrots | | Fuses | | JetPack 1000 | | JetPack 2000 | | Oil can | | Safe | | Sling | | TNT (1 stick) | | TNT (5 sticks) | +----------------+ 14 rows in set (0.00 sec) mysql> SELECT prod_name FROM products -> WHERE prod_name LIKE 'jet%'; #檢索一任何"jet"開頭的數據 +--------------+ | prod_name | +--------------+ | JetPack 1000 | | JetPack 2000 | +--------------+ 2 rows in set (0.00 sec) mysql> SELECT prod_name FROM products -> WHERE prod_name LIKE '%anvil%'; #'%anvil%'表示匹配任何位置包含文本anvil的值 +--------------+ | prod_name | +--------------+ | .5 ton anvil | | 1 ton anvil | | 2 ton anvil | +--------------+ 3 rows in set (0.00 sec) mysql> SELECT prod_name FROM products -> WHERE prod_name LIKE 's%e';
#找出以s開頭並一e結尾的所有產品
+-----------+ | prod_name | +-----------+ | Safe | +-----------+ 1 row in set (0.00 sec)*下劃線(_)通配符 用途與%一樣,但下劃線只匹配單個字符
eg: mysql> SELECT prod_name FROM products -> WHERE prod_name LIKE '_ ton anvil'; +-------------+ | prod_name | +-------------+ | 1 ton anvil | | 2 ton anvil | +-------------+ 2 rows in set (0.01 sec)
請對比%操作符的結果:
mysql> SELECT prod_name FROM products -> WHERE prod_name LIKE '% ton anvil'; +--------------+ | prod_name | +--------------+ | .5 ton anvil | | 1 ton anvil | | 2 ton anvil | +--------------+ 3 rows in set (0.00 sec)