1

I have a value "Berlin, Paris, London, ..." and I Want to do an MySQL Query

SELECT * FROM restaurants 
WHERE restaurant_city LIKE '%array%';

To get all restaurants where the city contains EITHER Berlin OR Paris OR London

How can I realize that?

5
  • where does the array come from and in which format? Commented Jul 29, 2015 at 11:46
  • SELECT * FROM restaurants WHERE restaurant_city IN ('Berlin','Paris','London'); Commented Jul 29, 2015 at 11:54
  • 1
    @Strawberry earlier I also understood it but Moskau wants to pass array instead of cities..... Commented Jul 29, 2015 at 12:00
  • You have to implode the array and passed it to query using REGEXP. Look at the answer below Commented Jul 29, 2015 at 12:01
  • @SantoshJagtap: OP doesn't have to. There are several tricks for this. We can also get it done from sql itself. Commented Jul 29, 2015 at 12:03

5 Answers 5

2

If in mysql we can do

SELECT * from restaurants where restaurant_city REGEXP 'Berlin|Paris|London';

Implode the given array using '|' and then use this generated string in query (In php).

$comma_separated = implode("|", $array);

Use the comma separated string in query

Sign up to request clarification or add additional context in comments.

4 Comments

Santhosh I think he is not mentioned PHP.
@kuttyraj Yes he not mentioned PHP. I edited my answer.
@kuttyraj: This question is tagged mysqli, Can we use mysqli without PHP ?
@RavinderReddy From his question, we might know that he is expecting sql result. Not PHP result. And It is not harder to do with normal SQL script. ;-)
1

Do a reverse trick.

SELECT * FROM restaurants WHERE 'array' LIKE concat('%',restaurant_city,'%')

So the query will be like:

SELECT * FROM Table1 WHERE 'Berlin, Paris, London' LIKE concat('%',restaurant_city,'%')

Sample in SQL Fiddle

Comments

1

Easiest way:

This is working fine.

 SELECT * FROM restaurants WHERE 
 restaurant_city LIKE '%Berlin%' OR 
 restaurant_city  LIKE '%Paris%' OR 
 restaurant_city  LIKE '%London%';

Or else, you could do same how Raging Bull mentioned.

See local sample test.

enter image description here

Comments

0

Try this

 SELECT * FROM restaurants WHERE ( restaurant_city LIKE '%Berlin%' OR  restaurant_city LIKE '%London%')

Worked on my case ...

Comments

-2

Try it-

SELECT * FROM restaurants 
WHERE find_in_set (restaurant_city,'Berlin,Paris,London');

2 Comments

I have edited my query as per understanding with problem, so please review your -ve voting.
who ever doing -ve voting should update his/her remarks....what is wrong here in this query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.