2017-04-11 42 views
2

是否有可能創建一個接受作爲參數,結果從查詢中設置一個MySQL的功能?創建一個接受結果集作爲參數的mysql函數?

基本上,我有很多的查詢將返回以下結果的結果集:

 
    id | score 
    70 | 25 
    71 | 7 
    72 | 215 
    74 | 32 
    75 | 710 
    76 | 34 
    78 | 998 
    79 | 103 
    80 | 3 

我想正常化值,使得他們來到一個範圍在0和1 的方式我之間以爲我會做到這一點是通過應用計算:

nscore = (score-min(score))/(max(score) - min(score))

得到以下結果

 
    id | score 
    70 | 0.022 
    71 | 0.004 
    72 | 0.213 
    74 | 0.029 
    75 | 0.710 
    76 | 0.031 
    78 | 1.000 
    79 | 0.100 
    80 | 0.000 

但我沒能拿出一個查詢來獲取與結果一起此查詢的最小值和最大值,因此想使用的功能(不能使用存儲過程),但不能就如何通過文檔結果集。

任何幫助表示讚賞!
謝謝!

編輯: 在結果的得分字段是一個計算字段。無法直接選擇它。

對於如:樣本查詢,返回上述結果 - select t.id as id, count(*) as score from tbl t inner join tbl2 t2 on t.idx = t2.idx where t2.role in (.....) 僅用於演示目的,而不是實際的模式或查詢

回答

1

號MySQL不支持用一個結果定義爲自變量的函數。

不幸的是,MySQL不支持通用表表達式(CTE),並且不支持分析功能。

要從MySQL查詢得到這樣的結果......一個辦法做到這一點在MySQL需要原來的查詢應退爲內嵌視圖,倍......

舉個例子:

SELECT t.id 
    , (t.score-s.min_score)/(s.max_score-s.min_score) AS normalized_score 
    FROM ( 
     -- original query here 
     SELECT id, score FROM ... 
     ) t 
CROSS 
    JOIN (SELECT MIN(r.score) AS min_score 
       , MAX(r.score) AS max_score 
      FROM (
        -- original query here 
        SELECT id, score FROM ... 
       ) r 
     ) s 
ORDER BY t.id 

編輯

基於查詢的加入問題...

SELECT q.id 
    , (q.score-s.min_score)/(s.max_score-s.min_score) AS normalized_score 
    FROM (-- original query goes here 
     -- ------------------------ 

        select t.id as id, count(*) as score 
        from tbl t 
        inner join tbl2 t2 on t.idx = t2.idx 
        where t2.role in (.....) 

     -- ------------------------ 
     ) q 
CROSS 
    JOIN (SELECT MIN(r.score) AS min_score 
       , MAX(r.score) AS max_score 
      FROM (-- original query goes here 
        -- ------------------------ 

        select t.id as id, count(*) as score 
        from tbl t 
        inner join tbl2 t2 on t.idx = t2.idx 
        where t2.role in (.....) 

        -- ------------------------ 
       ) r 
     ) s 
ORDER BY q.id 
+0

我很抱歉。忘了提及一個重要的細節。結果中的分數字段是一個計算字段。無法直接選擇它。編輯問題以反映這一點。 – arunondeck

+1

「計算場」不應該成爲問題。我們只需要一個返回有效結果集的查詢。完整的查詢進入parens。不幸的是,相同的查詢必須指定兩次。 – spencer7593

+0

是的長度是問題,尤其是當有多個連接。但是,猜猜這將不得不做。 謝謝@ spencer7593 – arunondeck

相關問題