Home > Database > Mysql Tutorial > How to Accurately Match Specific Values in Comma-Separated MySQL Strings?

How to Accurately Match Specific Values in Comma-Separated MySQL Strings?

Patricia Arquette
Release: 2025-01-22 21:32:10
Original
908 people have browsed it

How to Accurately Match Specific Values in Comma-Separated MySQL Strings?

Match specific values ​​in a comma separated MySQL string

When working with tables containing comma-separated values, it is often necessary to isolate specific values ​​within these strings. However, using the LIKE operator with the wildcard character (%) may result in unexpected matches.

Consider the COLORS field in the SHIRTS table, which contains values ​​such as '1,2,5,12,15'. A query like "SELECT * FROM shirts WHERE colors LIKE '%1%'" attempts to find all shirts with a red color (color=1). However, it also unexpectedly retrieves shirts with colors gray (color=12) and orange (color=15).

Solution:

1. Connecting commas:

The classic solution is to concatenate commas on the left and right sides of the string:

<code class="language-sql">SELECT * FROM shirts WHERE CONCAT(',', colors, ',') LIKE '%,1,%'</code>
Copy after login

This will add a comma before and after the string, ensuring that only exact matches (color=1) are selected.

2. Use find_in_set function:

Alternatively, you can use the find_in_set function to search for a specific value in a comma-separated string:

<code class="language-sql">SELECT * FROM shirts WHERE find_in_set('1', colors) > 0</code>
Copy after login

This function will return a non-zero value if the specified value is found in the string, effectively isolating shirts with color=1.

The above is the detailed content of How to Accurately Match Specific Values in Comma-Separated MySQL Strings?. 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