简体   繁体   English

SQL查询:选择记录,其中3个值在3列中

[英]SQL query : Select record where 3 values are in 3 columns

I have an input 1, 2 and 3. 我有输入1、2和3。

How to select a record where these values are in a row ? 如何选择这些值连续的记录?

SELECT * 
FROM table 
WHERE col1 IN (1, 2, 3) 
  AND col2 IN (1, 2, 3) 
  AND col3 in (1, 2, 3) 

If speed is needed, is it necessary also to index col1-col3 ? 如果需要速度,是否还需要索引col1-col3?

You should use OR not and .. if you need al least a single column match 如果至少需要单列匹配,则应使用OR not和..

  SELECT * 
  from table
  WHERE col1 in (1,2,3) 
  OR col2 in (1,2,3) 
  OR col3 in (1,2,3) ;

You query should work you have one of the value 1,2,3 in all the columns 您应该查询所有列中的值1,2,3之一

Tag the DBMS you are using in your question. 标记您正在使用的DBMS。

With that said, assuming you want to get those rows which have (1, 2, 3) in any order of columns col1, col2, col3 ie 如此说来,假设您要获取具有列col1,col2,col3的任意顺序的(1、2、3)的那些行,即

1 2 3
2 1 3
2 3 1
. . . 

In Oracle, MySQL and Postgresql, you can do this: 在Oracle,MySQL和Postgresql中,您可以执行以下操作:

select *
from t
where (1, 2, 3) in (
    (col1, col2, col3),
    (col1, col3, col2), 
    (col2, col1, col3), 
    (col2, col3, col1), 
    (col3, col1, col2), 
    (col3, col2, col1)
);

@Gurv has a reasonable solution, but you actually want the inverse. @Gurv有一个合理的解决方案,但是您实际上要求逆。 Assuming your database supports this tuple notation, you can do: 假设您的数据库支持该元组符号,则可以执行以下操作:

select *
from t
where (col1, col2, col3) in ( (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1) );

The advantage of this approach is that the database can use an index on (col1, col2, col3) . 这种方法的优点是数据库可以在(col1, col2, col3)上使用索引。

In other databases, you can use the same index and either or or union all : 在其他数据库中,可以使用相同的索引,或者使用orunion all

where (col1 = 1 and col2 = 2 and col3 = 3) or
      (col1 = 1 and col2 = 3 and col3 = 2) or
      . . .

The optimizer should be smart enough to use the index in this case. 在这种情况下,优化器应该足够聪明以使用索引。 If it is not, you can further encourage it with union / union all : 如果不是,您可以通过union / union all进一步鼓励它:

select t.*
from t
where (col1 = 1 and col2 = 2 and col3 = 3)
union all
select t.*
from t
where (col1 = 1 and col2 = 3 and col3 = 2) 
union all
. . .

A completely different approach which avoids the slow "where in" (but works obviously only on numeric fields) 一种完全不同的方法,可避免缓慢的“ where in”(但显然仅适用于数字字段)

select * from t where
max(col1, col2, col3) = max(1,2,3)
and 
min(col1, col2, col3) = min(1,2,3)
and
col1+col2+col3 - max(col1, col2, col3)- min(col1, col2, col3)
= 1+2+3 - max(1, 2, 3) - min(1, 2, 3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM