简体   繁体   English

sql查询根据匹配的列返回单个值

[英]sql query to return single value based on column it matches

I've a requirement where in if the query string matches column1 , return me 1. If it matches column 2 return 2 else if it matches column 3 return 3. 我有一个要求,如果查询字符串匹配column1,则返回1。如果它匹配2列,则返回2,否则,如果匹配3列则返回3。

Table strunctre: 表strunctre:

col1   col2    col3

11      12       13
22      23       24

If my query string is 23, then i'm expecting a return value of 2 as it matches col2. 如果我的查询字符串是23,那么我期望它的返回值2与col2匹配。

Something like below: 如下所示:

select 1 
from table1 
where col1=querystring 
      and orderid=xxx 
      or select 2 from table1 
         where col2=querystring 
               and orderid=xxx 
               or select 3 from table1 
                  where col3=querystring  and orderid=xxx 

Basically i'm expecting one query which return single value based on the column it matches. 基本上我期待一个查询,该查询根据匹配的列返回单个值。

Is it something doable in SQL as i'm not very good in DB skills. 因为我的数据库技能不是很好,所以它在SQL中可行吗?

Any help is highly appreciated. 非常感谢您的帮助。

There are a couple of approaches. 有两种方法。 If there is a guarantee that no more than one column will match at a time, a UNION will work: 如果保证一次最多匹配一列,则UNION将起作用:

SELECT 1 AS SomeCol 
FROM   table1 
WHERE  col1 = querystring 
       AND orderid = xxx 
UNION 
SELECT 2 
FROM   table1 
WHERE  col2 = querystring 
       AND orderid = xxx 
UNION 
SELECT 3 
FROM   table1 
WHERE  col3 = querystring 
       AND orderid = xxx; 

If more than one match can happen, another approach is this (note the order of precedence is now col1, col2, col3 etc): 如果可能发生多个匹配,则这是另一种方法(请注意,优先级现在是col1,col2,col3等):

SELECT CASE 
         WHEN col1 = querystring THEN 1 
         WHEN col2 = querystring THEN 2 
         WHEN col3 = querystring THEN 3 
       END AS SomeCol 
FROM   table1 
WHERE  orderid = xxx; 

Please try using case 请尝试使用case

declare @var int
set @var=23

select 
    case @var when col1 then 1
            when col2 then 2
            when col3 then 3 end
from YourTable 
where 
    col1=@var OR 
    col2=@var OR 
    col3=@var

尝试在查询中使用IF-ELSE条件,并检查传递的参数。

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

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