如何结合 MySQL WHERE 子句使用 LOCATE() 函数?
在 MySQL WHERE 子句中使用 LOCATE() 函数时,我们需要将子串作为第一个参数提供,并将表的列名作为第二个参数提供,同时使用一个比较运算符。下面是使用“学生”表进行演示的一个示例:
示例
假设我们在“学生”表中有以下值:
mysql> Select * from Student; +------+---------+---------+-----------+ | Id | Name | Address | Subject | +------+---------+---------+-----------+ | 1 | Gaurav | Delhi | Computers | | 2 | Aarav | Mumbai | History | | 15 | Harshit | Delhi | Commerce | | 20 | Gaurav | Jaipur | Computers | | 21 | Yashraj | NULL | Math | +------+---------+---------+-----------+ 5 rows in set (0.02 sec)
现在,以下查询展示了我们在 WHERE 子句中使用 LOCATE() 函数的方式
mysql> Select Name, LOCATE('av',name)As Result from student where LOCATE('av',Name) > 0; +--------+--------+ | Name | Result | +--------+--------+ | Gaurav | 5 | | Aarav | 4 | | Gaurav | 5 | +--------+--------+ 3 rows in set (0.00 sec) mysql> select name, LOCATE('av',name)As Result from student where LOCATE('av',Name)=0 ; +---------+--------+ | name | Result | +---------+--------+ | Harshit | 0 | | Yashraj | 0 | +---------+--------+ 2 rows in set (0.00 sec)
广告