python – 循环遍历Where语句直到找到结果(SQL)

问题摘要:

我正在使用Python从循环中向数据库(逐个)发送一系列查询,直到找到非空结果集.查询有三个必须满足的条件,它们放在where语句中.循环的每次迭代都会改变并操纵从特定条件到更通用条件的条件.

细节:

假设条件是基于按照准确度排序的预制列表的关键字,例如:

Option KEYWORD1   KEYWORD2   KEYWORD3 
  1     exact      exact      exact     # most accurate!
  2     generic    exact      exact     # accurate
  3     generic    generic    exact     # close enough
  4     generic    generic    generic   # close
  5     generic+   generic    generic   # almost there
  .... and so on.                      

在数据库方面,我有一个描述列,它应该包含特定形式或通用形式的所有三个关键字.当我在python中运行循环时,实际发生的是:

-- The first sql statement will be like

Select * 
From MyTable
Where Description LIKE 'keyword1-exact$' 
  AND Description LIKE 'keyword2-exact%' 
  AND Description LIKE 'keyword3-exact%'

-- if no results, the second sql statement will be like 

Select * 
From MyTable
Where Description LIKE 'keyword1-generic%' 
  AND Description LIKE 'keyword2-exact%' 
  AND Description LIKE 'keyword3-exact%'

-- if no results, the third sql statement will be like 

Select * 
From MyTable
Where Description LIKE 'keyword1-generic%' 
  AND Description LIKE 'keyword2-generic%' 
  AND Description LIKE 'keyword3-exact%'

-- and so on until a non-empty result set is found or all keywords were used

我正在使用上面的方法来获得最准确的结果,并且使用最少量的无关项(关键字越通用,结果就越不相关,他们将需要额外的处理)

题:

我上面的方法正是我想要的,但我确信它效率不高.

在查询而不是Python循环中执行此操作的正确方法是什么(知道我只有对数据库的读访问权限,因此我无法存储过程)?

最佳答案 这是一个想法

select top 1
    * 
from
(
    select
        MyTable.*,
        accuracy = case when description like keyword1 + '%'
            and description like keyword2 + '%'
            and description like keyword3 + '%'
        then accuracy
        end
    -- an example of data from MyTable
    from (select description = 'exact') MyTable
    cross join      
    (values 
        -- generate full list like this in python 
        -- or read it from a table if it is in database
        (1, ('exact'), ('exact'), ('exact')),
        (2, ('generic'), ('exact'), ('exact')),
        (3, ('generic'), ('generic'), ('exact'))
    ) t(accuracy, keyword1, keyword2, keyword3)
) t
where accuracy is not null
order by accuracy
点赞