Checking multiple columns for one value(为一个值检查多列)
问题描述
我有一个表格,其中包含这样的列,例如:
id,col1,col2,col3,col4现在,我想检查 col1, col2, col3, col4 的 ANY 是否有传入的值.
很长的路要走...
SELECT * FROM table WHERE (col1 = 123 OR col2 = 123 OR col3 = 123 OR col4 = 123);我猜它是 IN 的相反版本.
有没有更简单的方法来做我想做的事?
您可以使用 IN 谓词,如下所示:
SELECT * FROM table WHERE 123 IN(col1, col2, col3, col4);I have a table that has columns like this for example:
id,col1,col2,col3,col4
Now, I want to check if ANY of col1, col2, col3, col4 have the passed in value.
The long way to do it would be..
SELECT * FROM table WHERE (col1 = 123 OR col2 = 123 OR col3 = 123 OR col4 = 123);
I guess it's the opposite version of IN.
Is there an easier way to do what I want?
You can use the IN predicate, like so:
SELECT * FROM table WHERE 123 IN(col1, col2, col3, col4);
SQL Fiddle Demo
it's the opposite version of IN.
No it is not, It is the same as using the ORs the way you did in your question.
To clarify this:
The predicate IN or set membership is defined as1:
Where the Value Expression can be either 2:
So it is fine to do it this way, using the value expression 123, which is a literal.
1, 2: Images from: SQL Queries for Mere Mortals(R): A Hands-On Guide to Data Manipulation in SQL
这篇关于为一个值检查多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为一个值检查多列
基础教程推荐
- 在 SQL 中连接多个表 2021-01-01
- 无法解决整理冲突 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
