gpt4 book ai didi

mysql - 创建一个接受结果集作为参数的 mysql 函数?

转载 作者:行者123 更新时间:2023-11-29 02:45:19 24 4
gpt4 key购买 nike

是否可以创建一个 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

但我无法想出一个查询来获取此查询中的最小值和最大值以及结果,因此想到了使用函数(不能使用存储过程)但无法记录如何传递一个结果集。

感谢任何帮助!
谢谢!

编辑:结果中的分数字段是一个计算字段。不能直接选择。

例如:返回上述结果的示例查询 -
选择 t.id 作为 id,count(*) 作为分数
来自 tbl t
t.idx = t2.idx 上的内部连接 ​​tbl2 t2
其中 t2.role 在 (.....)
仅用于演示目的,并非实际架构或查询

最佳答案

没有。 MySQL 不支持定义以结果集作为参数的函数。

不幸的是,MySQL 不支持公用表表达式 (CTE),也不支持分析函数。

要从 MySQL 查询中获得此结果...在 MySQL 中执行此操作的一种方法需要将原始查询作为内联 View 返回,两次 ...

举个例子:

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

关于mysql - 创建一个接受结果集作为参数的 mysql 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43336544/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com