In MySQL, you can use the FIELD()
function to return the position of a given string or number within a list of arguments. The function returns the index (position) of the first argument in the list of subsequent arguments.
The syntax goes like this:
FIELD(str,str1,str2,str3,...)
Where str
is the item you want to find, and str1,str2,str3,...
is the list you’re searching through.
Here’s an example:
SELECT FIELD('Homer', 'Marge', 'Homer', 'Bart') AS 'Where is Homer?';
Result:
+-----------------+
| Where is Homer? |
+-----------------+
| 2 |
+-----------------+
In this example, the list is: 'Marge', 'Homer', 'Bart'
and we’re searching for the string Homer
within that list. And because Homer
is the 2nd item in the list of arguments, the result is 2
.
Continue reading →