Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Tìm vị trí index của chuỗi trong cột bảng MySQL bằng FIELD()

Hàm FIELD() tìm vị trí index của chuỗi trong danh sách các cột/giá trị. Bảng websites:

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)

Tìm index của 'For email' trong cột 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)

Kết quả: 'For email' ở index 1 của dòng 3 (cột purpose).

Tìm 'www.tutorialspoint.com':

mysql> SELECT FIELD('www.tutorialspoint.com', purpose, webaddress) FROM websites;
+------------------------------------------------------+
| FIELD('www.tutorialspoint.com', purpose, webaddress) |
+------------------------------------------------------+
| 2                                                    |
| 0                                                    |
| 0                                                    |
+------------------------------------------------------+
3 rows in set (0.00 sec)

Chuỗi ở index 2 của dòng 1 (cột webaddress).