mysql -- 匹配学习

我们知道在 MySQL 中使用 SQL SELECT 命令来读取数据, 同时我们可以在 SELECT 语句中使用 WHERE 子句来获取指定的记录。

WHERE 子句中可以使用等号 = 来设定获取数据的条件,如 "test_author = 'jingjing'"。

但是有时候我们需要获取 runoob_author 字段含有 "ing" 字符的所有记录,这时我们就需要在 WHERE 子句中使用 SQL LIKE 子句。

SQL LIKE 子句中使用百分号 %字符来表示任意字符,类似于Linux中或正则表达式中的星号 *。

如果没有使用百分号 %, LIKE 子句与等号 = 的效果是一样的。

mysql> select * from test_tbl;
+---------+------------+-------------+------------+
| test_id | test_title | test_author | test_time  |
+---------+------------+-------------+------------+
|       1 | memory     | zhiqing     | 2021-01-30 |
|       3 | CPU        | jieling     | 2021-01-31 |
|       4 | security   | jingjing    | 2021-01-31 |
|       5 | network    | jiejie      | 2021-01-31 |
+---------+------------+-------------+------------+
4 rows in set (0.00 sec)

mysql> select * from test_tbl where test_author like "%ing";
+---------+------------+-------------+------------+
| test_id | test_title | test_author | test_time  |
+---------+------------+-------------+------------+
|       1 | memory     | zhiqing     | 2021-01-30 |
|       3 | CPU        | jieling     | 2021-01-31 |
|       4 | security   | jingjing    | 2021-01-31 |
+---------+------------+-------------+------------+
3 rows in set (0.00 sec)

mysql>

mysql> select * from test_tbl where test_author like "%g";## 在test_author中有结尾是g的数据
+---------+------------+-------------+------------+
| test_id | test_title | test_author | test_time |
+---------+------------+-------------+------------+
| 1 | memory | zhiqing | 2021-01-30 |
| 3 | CPU | jieling | 2021-01-31 |
| 4 | security | jingjing | 2021-01-31 |
+---------+------------+-------------+------------+
3 rows in set (0.00 sec)

mysql> select * from test_tbl where test_author like "%e%"; ##在test_author 中含有e的数据
+---------+------------+-------------+------------+
| test_id | test_title | test_author | test_time |
+---------+------------+-------------+------------+
| 3 | CPU | jieling | 2021-01-31 |
| 5 | network | jiejie | 2021-01-31 |
+---------+------------+-------------+------------+
2 rows in set (0.00 sec)

mysql> select * from test_tbl where test_author like "j%"; ## 在test_author中有开头是j的数据
+---------+------------+-------------+------------+
| test_id | test_title | test_author | test_time |
+---------+------------+-------------+------------+
| 3 | CPU | jieling | 2021-01-31 |
| 4 | security | jingjing | 2021-01-31 |
| 5 | network | jiejie | 2021-01-31 |
+---------+------------+-------------+------------+
3 rows in set (0.01 sec)

mysql>

也可以在update /delete 中使用like ,

like 匹配/模糊匹配,会与 % 和 _ 结合使用。

'%a'     //以a结尾的数据
'a%'     //以a开头的数据
'%a%'    //含有a的数据
'_a_'    //三位且中间字母是a的
'_a'     //两位且结尾字母是a的
'a_'     //两位且开头字母是a的

posted @ 2021-02-02 15:25  正霜霜儿  阅读(157)  评论(0编辑  收藏  举报