【问题标题】:SQL Ignore non matching columnsSQL忽略不匹配的列
【发布时间】:2021-07-03 21:09:33
【问题描述】:

我正在尝试开发一个在表上进行选择的存储过程。存储过程有 4 个输入:Input1、Input2、Input3、Input4。

表格有 4 列:Col1、Col2、Col3、Col4。

要求是如果所有选择都不匹配,我们需要忽略它并选择选择下一个:

用例:

Select * 
from table 
where Col1=Input1 
  and Col2=Input2 
  and Col3=Input3 
  and Col4=Input4;

如果由于 Col2 不等于 Input2 导致条件没有返回,select 需要忽略它并尝试匹配其他类似:

Select * 
from table 
where Col1=Input1 
  and Col3=Input3 
  and Col4=Input4;

它应该一直这样直到响应的最后一个可能选项:

Select * 
from table 
where Col1=Input1;

如果有办法请帮忙,提前谢谢。

【问题讨论】:

  • 即使您将问题限制在单个 RDBMS 中,它仍然过于宽泛。
  • 请指定您的 DMS - 它不能是 Db2 和 MYSQL。您没有提供所需逻辑的足够详细信息 - 您描述它的方式可以在 WHERE 条件下执行简单的 Col1=Input1 OR Col2 = Imput2 OR Col3=Input3 OR Col4=Input4。
  • 我删除了冲突的 DBMS 标签。请为您真正使用的数据库产品添加一个标签。
  • 为什么最后一个选项不是表中的所有行?问题不清楚。除了包括数据库之外,您还应该展示一个您想要的组合示例。以及当不同的参数集返回行时该怎么办。
  • @MichaelTiefenbacher 数据库是 DB2。 OR 条件的问题是要匹配尽可能多的条件。例如,如果有一条记录在所有 4 个条件下都匹配,我们希望使用它。否则,需要知道哪些列不匹配并尝试其他列。按优先级执行此操作,直到最后一个可能的选项。示例如下: 查询:Col1+ Col2 + Col3 + Col4 + Col5 查询:Col1 + Col2 + Col3 + Col4 查询:Col1 + Col2 + Col3 查询:Col1 + Col2 查询:Col1 查询:默认

标签: sql stored-procedures db2


【解决方案1】:

正如 cmets 中提到的,这个问题有点模糊,所以恐怕任何答案也会有点模糊。你可以这样做:

select top 1 *,
case when Coll=input1 then 1 else 0 end as match1,
case when Col2=input2 then 1 else 0 end as match2,
case when Col3=input3 then 1 else 0 end as match3,
case when Col4=input4 then 1 else 0 end as match4
from table
order by match1+match2+match3+match4 desc

这是假设 SQL Server 作为 DBMS(例如,如果是 Oracle,您可能需要使用 LIMIT 而不是 TOP),并且我还假设列在匹配方面具有相同的权重。 另外,我假设您只想要一个最佳匹配项,如果不是,您可能需要对 TOP 进行一些更改和/或使用 where 子句。 最后,如果您的列和/或输入可以为空,您可能需要使用 isnull()。

【讨论】:

  • 如果查询预期返回多于一行,则此逻辑不起作用。但这是对问题的巧妙解释。
【解决方案2】:

嗯。 . .一种方法是:

select t.*
from (select t.*,
             sum(case when condition1 then 1 else 0 end) over () as c_1,
             sum(case when condition1 and condition2 then 1 else 0 end) over () as c_12,
             sum(case when condition1 and condition2 and condition3 then 1 else 0 end) over () as c_123,
             sum(case when condition1 and condition2 and condition3 and condition4 then 1 else 0 end) over () as c_1234
      from t
     ) t
where (c_1234 > 0 and condition1 and condition2 and condition3 and condition4) or
      (c_1234 = 0 and c_123 > 0 and condition1 and condition2 and condition3) and
      (c_123 = 0 and c_12 > 0 and condition1 and condition2 ) and
      (c_12 = 0 and c_1 > 0 and condition1 ) ;
  

根据条件和其他考虑因素(例如您是否只期望一行),可能会有更简单的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    • 2010-12-07
    • 2020-02-12
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 2017-03-11
    相关资源
    最近更新 更多