简体   繁体   中英

SELECT WHERE any value in csv in array

Suppose I have this array:

$city = ["toronto", "chicago", "potato"];

and my table looks like this:

Table Name: city_table
id    city
1     toronto, orlando
2     buffalo, toledo
3     orlando, tomato
4     potato, chicago, nanaimo

Is it possible to have a query that gives me this result?

id    city
1     toronto, orlando
4     potato, chicago, nanaimo

I tried this but it obviously doesn't work:

$city_string = "'toronto', 'chicago', 'potato'";
SELECT * from city_table WHERE city IN $city_string

To search a comma-separated value in MySQL you use FIND_IN_SET . It can only search for 1 item at a time, so you need to call it separately for each name $city , and combine them with AND .

SELECT *
FROM city_table
WHERE FIND_IN_SET('$city[0]', city_table)
OR FIND_IN_SET('$city[1]', city_table)
OR FIND_IN_SET('$city[2]', city_table)

In your actual code you should use implode() to construct the WHERE clause dynamically.

Note that you should not have spaces after the commas in the table, FIND_IN_SET will not work with the CSV the way you've written it.

However, it would be better to normalize your schema so you don't have a comma-separated value. FIND_IN_SET can't be optimized with an index, so it will have to perform a full table scan.

You can use FIND_IN_SET at MySQL.

Example

SELECT *
FROM city_table
WHERE FIND_IN_SET('$city[0]', city_table)
AND FIND_IN_SET('$city[1]', city_table)
AND FIND_IN_SET('$city[2]', city_table)

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