简体   繁体   中英

MYSQL: select rows where a column contains a more string?

In my table, I have this situation:

+-------+---------------+--------------+----------+
|  ID   |     CODE      |    VALUE     |   Etc... |
+-------+---------------+--------------+----------+
|   1   |    10a10a     | a1, b1, a2,  |          |
|       |               | c1, c5, e7   |          |
+-------+---------------+--------------+----------+
|   2   |    15cef1     | b1, n6, p1,  |          |
|       |               | y3, e7, d9   |          |
+-------+---------------+--------------+----------+
|                                                 |
|                    Etc....                      |

When I run the following query:

 SELECT * FROM code WHERE value IN ('10a10a') AND facilities LIKE ('%b1%')

I regularly get the response from the server. But, performing the query with facilities LIKE ('%b1%', '%c5%') the server returns no results.

What is the correct way to search for multiple values in the same column?

You can query that with separate OR clauses.

SELECT * FROM code WHERE value IN ('10a10a') AND (facilities LIKE ('%b1%') OR facilities LIKE ('%c5%'))

Note the grouping of the OR statements surrounded by the extra brackets.

However, storing multiple values like that in the 'Value' column if you require to query on it, probably means the Value column should be normalised and moved to its own separate table, which you can then query using JOIN statements, and without the overhead of wildcard patterns using the LIKE operator.

您需要使用 或 在寻找 2 个类似值时:

 WHERE facilities LIKE '1b1%' OR facilities LIKE '%c5%'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM