如何結合 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)

更新時間:2020 年 2 月 4 日

564 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始學習
廣告
© . All rights reserved.