首页 > 解决方案 > 用于检查数据库中是否存在 3 个连续值的 SQL 查询?

问题描述

我正在尝试查询数据库以检查数据库字段中是否存在 3 个值(例如:us、uk、usr),如果存在它应该返回 true,否则它必须返回不存在的值。

Select  ( case  when  exists ( select Detail
                               from Application
                               where EmpID = '123' and Detail = ?
                              )
                then 1  
                else 0  
           end )

结果应返回此类 = US(数据库中不存在) 在此处输入图像描述

标签: sqlsql-server

解决方案


Select  ( case  when  exists ( select Detail
                                   from Application
                                   where EmpID = '123' and Detail IN ('us', 'uk', 'usr')
                                  )
                    then 1  
                    else 0  
               end )

编辑

无论如何要返回表中不存在的值而不是 0 或 1(例如:美国)-?

select case when Detail IN ('us', 'uk', 'usr')
            then Detail
            else '-'
        end
from Application
where EmpID = '123'

编辑 2

但是它返回数据库中存在的值,我如何修改它以返回数据库中不存在的值?

Select  ( case  when  exists ( select Detail
                               from Application
                               where EmpID = '123'
                              )
                then (select case when Detail IN ('us', 'uk', 'usr')
                                  then Detail
                                  else '-'
                             end
                      from Application
                      where EmpID = '123' 
                      )
                else '-'  
           end )

推荐阅读