python – 循环遍历Where语句直到找到结果(SQL)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 循环遍历Where语句直到找到结果(SQL),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2199字,纯文字阅读大概需要4分钟。
内容图文
问题摘要:
我正在使用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
内容总结
以上是互联网集市为您收集整理的python – 循环遍历Where语句直到找到结果(SQL)全部内容,希望文章能够帮你解决python – 循环遍历Where语句直到找到结果(SQL)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。