我正在使用排名算法编写搜索例程,并希望一次性通过。
我的理想查询将是这样的...。
select *, (select top 1 wordposition
from wordpositions
where recordid=items.pk_itemid and wordid=79588 and nextwordid=64502
) as WordPos,
case when WordPos<11 then 1 else case WordPos<50 then 2 else case WordPos<100 then 3 else 4 end end end end as rank
from items
是否可以在这种情况下使用WordPos?它对我产生错误,列名'WordPos'无效。
我知道我可以为每种情况重做子查询,但我认为它实际上会重新运行该情况,不是吗?
例如:
select *, case when (select top 1 wordposition from wordpositions where recordid=items.pk_itemid and wordid=79588 and nextwordid=64502)<11 then 1 else case (select top 1 wordposition from wordpositions where recordid=items.pk_itemid and wordid=79588 and nextwordid=64502)<50 then 2 else case (select top 1 wordposition from wordpositions where recordid=items.pk_itemid and wordid=79588 and nextwordid=64502)<100 then 3 else 4 end end end end as rank from items
那行得通.....但是否真的每次都会重新运行相同的查询?
很难从测试中看出来,因为它第一次运行很慢,但是随后的运行很快....它正在缓存...所以这意味着它第一次运行它时是第一行,随后是它的三倍。将从缓存中获取结果?
很好奇,做到这一点的最佳方法是...谢谢!瑞安
您可以使用子查询来执行此操作。我将坚持使用您的SQL Server语法,即使问题被标记为mysql:
select i.*,
(case when WordPos < 11 then 1
when WordPos < 50 then 2
when WordPos < 100 then 3
else 4
end) as rank
from (select i.*,
(select top 1 wpwordposition
from wordpositions wp
where recordid=i.pk_itemid and wordid=79588 and nextwordid=64502
) as WordPos
from items i
) i;
这也简化了case
声明。您不需要嵌套的case语句来处理多个条件,只需多个where
子句即可。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句