Trả lời: INSTR() hoặc LOCATE()
MySQL không có stripos() (case-insensitive position). Tương đương:
INSTR(str, substr): Trả về vị trí (1-based) lần đầu tìm thấy. Case-insensitive mặc định.
LOCATE(substr, str): Tham số đảo ngược, có vị trí bắt đầu.
Ví dụ minh họa
Tạo bảng
mysql> CREATE TABLE DemoTable (Title TEXT);
mysql> INSERT INTO DemoTable VALUES('MySQL is my favourite subject');
mysql> INSERT INTO DemoTable VALUES('MongoDB is not my favourite subject');
Dữ liệu gốc
+-------------------------------------+
| Title |
+-------------------------------------+
| MySQL is my favourite subject |
| MongoDB is not my favourite subject |
+-------------------------------------+
Truy vấn INSTR
mysql> SELECT INSTR(Title, 'favourite') AS Position FROM DemoTable;
Kết quả
+----------+
| Position |
+----------+
| 13 |
| 19 |
+----------+
INSTR vs LOCATE
| Hàm | Cú pháp | Vị trí bắt đầu | Case-sensitive |
INSTR(str, substr) | str, substr | Luôn từ 1 | Tuân theo collation |
LOCATE(substr, str) | substr, str | Từ 1 | Tuân theo collation |
LOCATE(substr, str, pos) | substr, str, pos | Từ pos | Tuân theo collation |
Case-sensitive search
-- Dùng COLLATE
SELECT INSTR(Title COLLATE utf8mb4_bin, 'favourite') FROM DemoTable;
-- Hoặc BINARY
SELECT INSTR(BINARY Title, 'favourite') FROM DemoTable;
So sánh với PHP stripos
| Đặc điểm | PHP stripos() | MySQL INSTR() |
| Case-sensitive | Không (insensitive) | Tuân theo collation (mặc định insensitive) |
| Vị trí bắt đầu | 0-based | 1-based (0 = không tìm thấy) |
| Không tìm thấy | false | 0 |
| Offset | Có (parameter 3) | Dùng LOCATE(substr, str, pos) |
Ứng dụng: Tìm vị trí từ khóa
SELECT
Title,
INSTR(LOWER(Title), 'mysql') AS pos_mysql,
INSTR(LOWER(Title), 'mongodb') AS pos_mongodb
FROM DemoTable;
Lưu ý
- INSTR/LOCATE không dùng index (full scan)
- Cần tìm kiếm fulltext → dùng FULLTEXT INDEX + MATCH() AGAINST()
- MySQL 8.0+:
REGEXP_INSTR() cho regex position