Home > Database > Mysql Tutorial > body text

How to Efficiently Match Multiple Words in MySQL Records Using LIKE or REGEXP?

Patricia Arquette
Release: 2024-11-26 02:15:10
Original
868 people have browsed it

How to Efficiently Match Multiple Words in MySQL Records Using LIKE or REGEXP?

Matching Multiple Words in MySQL Records Using LIKE or REGEXP

When using the LIKE operator to search for records containing specific words, you may encounter difficulties if the words appear at different positions in the field. To address this issue, consider using the REGEXP operator.

For example, let's say you have a table named 'table' with a field called 'name' that contains the value 'Stylus Photo 2100.' Using the LIKE operator, the following query:

SELECT `name` FROM `table` WHERE `name` LIKE '%Stylus 2100%'
Copy after login

will return no results. This is because the LIKE operator searches for an exact match of the specified string.

To find records containing the words 'Stylus' and '2100' in any order, you can use the REGEXP operator, as seen in this query:

SELECT `name` FROM `table` WHERE `name` REGEXP 'Stylus.+2100'
Copy after login

This query will use a regular expression to search for records where the 'name' field contains the word 'Stylus' followed by any number of characters (indicated by the '.'), and then the word '2100.'

Alternatively, you can use the LIKE operator multiple times, as shown in this query:

SELECT `name` FROM `table` WHERE `name` LIKE '%Stylus%' AND `name` LIKE '%2100%'
Copy after login

This query will return records where the 'name' field contains the word 'Stylus' and the word '2100', regardless of their position.

The above is the detailed content of How to Efficiently Match Multiple Words in MySQL Records Using LIKE or REGEXP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template