Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an SQL statement to use "LIKE" for nine different values? [duplicate]

Tags:

sql

logic

I have to select all the records where:

where FIELD2 like '%value21%'
or FIELD2 like '%value22%'
or FIELD2 like '%value23%'
-- repeat up to
or FIELD2 like '%value29%'

Here, value21, ..., value29 are parameters which the user can put in a form before submitting the query. They are (not subsequent) numerical codes, and FIELD2 is a database column holding a string value.

Which is the most compact form to write down my SQL query?

Note: This is related to an earlier question, but this needs LIKE rather than equals.

like image 655
tic Avatar asked Oct 14 '10 17:10

tic


1 Answers

I'm afraid you're stuck with:

  WHERE (FIELD2 LIKE '%value21' OR 
         FIELD2 LIKE '%value22' OR 
         FIELD2 LIKE '%value23' ...)

at least in standard SQL (your particular engine might offer some form of full-text indexing that would help).

A query like this often indicates a normalization problem in your database design with multiple values stored in a single field value. If that's true in your case and you have any degree of control over the database schema, I advise fixing the problem as soon as possible. Otherwise check your medical coverage to make sure it covers SQL-induced psychosis — this can drive you crazy.

like image 171
Larry Lustig Avatar answered Oct 12 '22 13:10

Larry Lustig