在MariaDB中,当操作需要完全匹配时,LIKE
子句与SELECT
语句一起使用来检索数据。它可以与SELECT
,INSERT
,UPDATE
和DELETE
语句一起使用。
它用于模式匹配并返回true
或false
。用于比较的模式接受以下通配符:
"%"
通配符:匹配字符数(0或更多)。"_"
通配符:匹配单个字符。它匹配其集合中的字符。语法:
SELECT field, field2,... FROM table_name, table_name2,... WHERE field LIKE condition
假设我们有一个students
表,并有以下数据。
MariaDB [testdb]> select * from students; +------------+--------------+-----------------+----------------+ | student_id | student_name | student_address | admission_date | +------------+--------------+-----------------+----------------+ | 1 | Maxsu | Haikou | 2017-01-07 | | 3 | JMaster | Beijing | 2016-05-07 | | 4 | Mahesh | Guangzhou | 2016-06-07 | | 5 | Kobe | Shanghai | 2016-02-07 | | 6 | Blaba | Shengzhen | 2016-08-07 | | 7 | Maxsu | Sanya | 2017-08-08 | +------------+--------------+-----------------+----------------+ rows in set (0.00 sec)
现在想要查询那些名字以Ma
字母开头的所有学生信息,那么就可以使用LIKE
条件的%
通配符来查找所有以Ma
开头的名字。参考以下查询语句 -
SELECT student_name FROM students WHERE student_name LIKE 'Ma%';
执行上面查询语句,得到以下结果 -
MariaDB [testdb]> SELECT student_name -> FROM students -> WHERE student_name LIKE 'Ma%'; +--------------+ | student_name | +--------------+ | Maxsu | | Mahesh | | Maxsu | +--------------+ rows in set (0.07 sec)
也可以在同一个字符串中多次使用%
通配符。例如,要查询名字中包含'Ma'
字符的所有记录 -
SELECT student_name FROM students WHERE student_name LIKE '%Ma%';
执行上面查询语句,得到以下结果 -
MariaDB [testdb]> SELECT student_name -> FROM students -> WHERE student_name LIKE '%Ma%'; +--------------+ | student_name | +--------------+ | Maxsu | | JMaster | | Mahesh | | Maxsu | +--------------+ rows in set (0.00 sec)
使用带LIKE
条件的通配符。`(下划线)通配符只检查一个字符。下面语句将查询名字为
“Max_u”`的学生信息。
SELECT * FROM students WHERE student_name LIKE 'Max_u';
执行上面查询语句,得到以下结果 -
MariaDB [testdb]> SELECT * -> FROM students -> WHERE student_name LIKE 'Max_u'; +------------+--------------+-----------------+----------------+ | student_id | student_name | student_address | admission_date | +------------+--------------+-----------------+----------------+ | 1 | Maxsu | Haikou | 2017-01-07 | | 7 | Maxsu | Sanya | 2017-08-08 | +------------+--------------+-----------------+----------------+ rows in set (0.00 sec)
在MariaDB中,LIKE
子句可以使用NOT
运算符。在NOT
运算符中使用%
通配符。 在这个示例中,将是查询名字不是以"Ma"
开头的所有学生信息。
SELECT * FROM students WHERE student_name NOT LIKE 'Ma%';
执行上面查询语句,得到以下结果 -
MariaDB [testdb]> SELECT * -> FROM students -> WHERE student_name NOT LIKE 'Ma%'; +------------+--------------+-----------------+----------------+ | student_id | student_name | student_address | admission_date | +------------+--------------+-----------------+----------------+ | 3 | JMaster | Beijing | 2016-05-07 | | 5 | Kobe | Shanghai | 2016-02-07 | | 6 | Blaba | Shengzhen | 2016-08-07 | +------------+--------------+-----------------+----------------+ rows in set (0.00 sec)