如何编写 SQL 语句以对九个不同的值使用“LIKE”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3936258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 07:56:32  来源:igfitidea点击:

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

sqllogic

提问by tic

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, ..., value29are parameters which the user can put in a form before submitting the query. They are (not subsequent) numerical codes, and FIELD2is a database column holding a string value.

这里, value21, ...,value29是用户可以在提交查询之前放入表单的参数。它们是(不是后续)数字代码,并且FIELD2是保存字符串值的数据库列。

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

写下我的 SQL 查询的最紧凑的形式是什么?

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

注意:这与之前的问题有关,但这需要LIKE而不是等于。

回答by Larry Lustig

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).

至少在标准 SQL 中(您的特定引擎可能会提供某种形式的全文索引,这会有所帮助)。

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.

像这样的查询通常表明数据库设计中存在规范化问题,多个值存储在单个字段值中。如果您的情况确实如此,并且您对数据库架构有任何程度的控制,我建议您尽快解决问题。否则,请检查您的医疗保险以确保它涵盖 SQL 引起的精神病——这可能会让您发疯。

回答by NotMe

One way:

单程:

select Field1, Field2 from Table where Field2 like '%val%'
UNION
select Field1, Field2 from Table where Field2 like '%val2%'
UNION
select Field1, Field2 from Table where Field2 like '%val2%'

etc.

等等。