Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to combine IN and LIKE in MySQL?

Tags:

mysql

sql-like

I'm currently running a query like this:

SELECT *
  FROM email
 WHERE email_address LIKE 'ajones@%'
    OR email_address LIKE 'bsmith@%'
    OR email_address LIKE 'cjohnson@%'

The large number of OR's bothers me. Is there a way to condense this up with something akin to an IN operator, e.g.:

SELECT *
  FROM email 
 WHERE email_address LIKE ('ajones@%', 'bsmith@%', 'cjohnson@%')

Or is this just wishful thinking?

like image 377
abeger Avatar asked May 24 '10 20:05

abeger


2 Answers

You can use RLIKE operator (synonym for REGEXP) as well.

SELECT *
  FROM email 
 WHERE email_address RLIKE 'ajones@|bsmith@|cjohnson@'

There might be some performance penalty due to regex matching, but for simple patterns or small sets it should be not an issue. For more on RLIKE see http://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_regexp

like image 196
Daniel Harcek Avatar answered Nov 04 '22 21:11

Daniel Harcek


Here's what I recommend: Extract the part of the email address before the @ and use that before IN:

SELECT * FROM `email`
WHERE LEFT(`email_address`, LOCATE('@', `email_address`) - 1)
        IN ('ajones', 'bsmith', 'cjohnson')
like image 30
Jordan Running Avatar answered Nov 04 '22 22:11

Jordan Running