MySQL 如何在MySQL表的列中查找存储为记录的字符串的索引位置?
我们可以使用FIELD()函数来查找在MySQL表的列中存储为记录的字符串的索引位置。为了演示它,我们使用名为“websites”的表,其中包含以下数据。
阅读更多:MySQL 教程
例子
mysql> Select * from websites;
+----+---------------+------------------------+
| Id | Purpose | Webaddress |
+----+---------------+------------------------+
| 1 | For tutorials | www.tutorialspoint.com |
| 2 | For searching | www.google.co.in |
| 3 | For email | www.gmail.com |
+----+---------------+------------------------+
3 rows in set (0.00 sec)
现在,假设我们想要查找特定字符串(比如“for email”)在表的“Purpose”和“Webaddress”两列中存储为记录的字符串中的索引号,下面的查询就可以完成这个任务。
mysql> Select FIELD('For email', purpose, webaddress) From websites;
+----------------------------------------+
| FIELD('For email', purpose, webaddress)|
+----------------------------------------+
| 0 |
| 0 |
| 1 |
+----------------------------------------+
3 rows in set (0.00 sec)
上面的结果集显示,“For email”字符串在第三行的第一个索引位置上。
mysql> Select FIELD('www.tutorialspoint.com', purpose, web address) From websites;
+------------------------------------------------------+
| FIELD('www.tutorialspoint.com', purpose, web address)|
+------------------------------------------------------+
| 2 |
| 0 |
| 0 |
+------------------------------------------------------+
3 rows in set (0.00 sec)
上面的结果集显示,“www.tutorialspoint.com”字符串在第一行的第二个索引位置上。