2013-11-01 63 views
1

我正在用排名算法編寫一個搜索例程,希望能夠一次通過。是否可以在同一個外部查詢的case語句中使用子查詢的結果?

我的理想查詢會是這樣的....

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 

這一工程....但它真的重新運行每次查詢相同?

從測試中很難判斷出它第一次運行很慢,但後續運行很快......它是緩存......所以這意味着它第一次運行它的第一行,後續三次它會從緩存中得到結果?

只是好奇最好的辦法是做什麼... 謝謝! output子句(它來自一個子查詢的事實是無關緊要的)不能同一SELECT語句中使用中介紹 瑞安

+0

對不起T-SQL不是MySQL ...修正了標籤... –

回答

1

你可以使用子查詢來做到這一點。我會堅持你的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子句。

+0

工作感謝!兩個答案都是正確的...我選擇這個例子是因爲這個例子可以直接在我的項目中使用。另外感謝提供簡化案例的提示! –

0

號標識。

這裏有一些解決方案:

  1. 使用JOIN 重寫查詢,這將完全消除這個問題,並與RA合身。
  2. 用大小寫將另一個SELECT中的子查詢換成整個SELECT。 外部的 select可以訪問由內部SELECT的輸出子句引入的標識符。
  3. 使用CTE(如果是SQL Server)。這與#2類似,因爲它允許引入標識符。

雖然「重寫」的子查詢每一種情況下是非常雜亂應該還是導致相當的計劃 - 但查看查詢個人資料! - 由於查詢的結果是非易失性的。因此,查詢計劃器可以安全地移動等價的子查詢,查詢計劃器應該將子查詢/子查詢移動到JOIN以避免任何「重新運行」。


這裏是使用JOIN,這是我的優選方法的轉換。 (我覺得,如果查詢不能在JOIN「容易」,那麼它可能會問了錯誤的事情或其他方面來寫是展示與架構設計問題。)

select 
    wp.wordposition as WordPos, 
    case wp.wordposition .. as Rank 
from items i 
left join wordpositions wp 
    on wp.recordid = i.pk_itemid 
where wp.wordid = 79588 
    and wp.nextwordid = 64502 

我做關於這裏多重性的假設(即wordid是唯一的)應該被驗證。如果這種多重性是無效的,否則不可糾正(並且您的確在使用SQL Server),那麼我建議使用ROW_NUMBER()和CTE。

相關問題