0

I am trying to write the following statement without the SQL OR:

SELECT * FROM table WHERE names LIKE 'john%' OR names LIKE 'brian%'

So, I don't want to use OR because the names in my real problem are too many, but I also don't want to use REGEXP. How is the LIKE syntax? Thank you in advance!

I don't want to use REGEXP because some names are in square brackets and others or not. And this make it too complicated. I just want to know if there is a syntax similar to 'REGEXP '^(".implode("|", $names_array).")[[:>:]]'";' using LIKE

8
  • If you want records of people whose name start with John or Brian, I think your query is just fine. Make sure you index names field Commented Sep 17, 2015 at 14:56
  • possible duplicate of mySQL regex in the where clause Commented Sep 17, 2015 at 14:57
  • no, I said in the question, I have many names saved in an array. If I used REGEXP I would do this with implode and | as an OR. Something like this: 'REGEXP '^(".implode("|", $names_array).")[[:>:]]'";' But I need a similar syntax for LIKE Commented Sep 17, 2015 at 14:58
  • What about: SELECT * FROM table WHERE LEFT(names, 4) = 'john' OR LEFT(names, 5) = 'brian' as this should cover your needs? Commented Sep 17, 2015 at 14:59
  • 2
    Why do you want to use LIKE and not REGEXP? You cannot do what you want with LIKE, LIKE only have _ (one character) and % (any characters) symbol, you won't be able to create anything similar to a OR using LIKE. Commented Sep 17, 2015 at 15:02

1 Answer 1

1

Use REGEX:

SELECT * FROM `table`
  WHERE `names`
  REGEX '^(john|brian)+'
Sign up to request clarification or add additional context in comments.

3 Comments

Correct me if I'm wrong but won't this only match names like "john" "johnjohn" "brianjohnbrian" etc ?
@Emi1305, no ^$ anchors here. So, 111john222 matches too.
Correct regex is ^(john|brian)

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.