我正在处理以下形式的表格:
A B
------ -----------
1 value1
2 value2
3 value3
-1 value4
在此表中,值 -1
表示一个包罗万象,如果该列中没有与 A
的其他匹配项。这意味着,对 A = 2
的查询应该返回一条记录,其中 value2
是列 B 的值。如果查询表,比方说,A = 6
,那么 B 的值应该是 value4
(因为它是与 catch all 关联的值)。
实现此目标的“最佳”查询是什么?有更好的解决方案吗?我在 SQLFiddle 中编写了一个小的设置示例脚本,如果有帮助的话。
数据库是SQL Server。
你能帮忙吗?非常感谢。
最佳答案
select top (1) A, B
from (
select A, B, 0 as priority from t where A = @value
union
select A, B, 1 from t where A = -1
) foo
order by priority
关于SQL 查询以检索值或全部捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11674599/