Home > Database > Mysql Tutorial > How Can I Find MySQL Rows Contained Within a Specific String?

How Can I Find MySQL Rows Contained Within a Specific String?

Mary-Kate Olsen
Release: 2024-12-25 22:23:10
Original
553 people have browsed it

How Can I Find MySQL Rows Contained Within a Specific String?

Finding Rows Containing a Query String: The Reverse of LIKE Operator

In MySQL, the LIKE operator is commonly used to search for rows that contain a specified text pattern. For instance, a query like:

SELECT name FROM user WHERE name LIKE "%john%"
Copy after login

would return records such as "John Smith" and "Peter Johnson." However, what if you need to do the opposite operation? That is, find rows that themselves contain a given string within them.

Achieving the Reverse of LIKE

To find rows that are contained within a query string, you can utilize a combination of the LIKE operator and the CONCAT() function. Here's an example:

SELECT name FROM user 
WHERE 'John Smith and Peter Johnson are best friends' LIKE
  CONCAT('%', name, '%')
Copy after login

In this query, the CONCAT() function joins a wildcard character (%) with the name field to create a pattern:

%name%
Copy after login

The LIKE operator then matches this pattern against the provided string, identifying all rows that contain names found within it. So, in this case, it would retrieve "John Smith" and "Peter Johnson."

This technique allows you to search for rows that are contained within a larger string, effectively reversing the functionality of the LIKE operator and providing a flexible way to find specific data within a database.

The above is the detailed content of How Can I Find MySQL Rows Contained Within a Specific String?. 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