[英]How can I store the result of a function into a variable?
Please take a look at it: 请看一下:
SELECT calculate_both_score_and_reputation(u.id) AS sr FROM users u
It returns something like this: 它返回如下内容:
+----------+
| sr |
+----------+
| 0,1322 |
| 3, 232 |
| -2, 9978 |
| 31, 5745 |
+----------+
Now I want to split the result of that function into two different columns: 现在,我想将该函数的结果分为两个不同的列:
SELECT SUBSTRING_INDEX(calculate_both_score_and_reputation(u.id),',', 1) AS s,
SUBSTRING_INDEX(calculate_both_score_and_reputation(u.id),',', -1) AS r,
FROM users u
Here is the result: 结果如下:
+----+------+
| s | r |
+----+------+
| 0 | 1322 |
| 3 | 232 |
| -2 | 9978 |
| 31 | 5745 |
+----+------+
The result is as expected. 结果是预期的。 But as you see, that function will be called twice. 但是如您所见,该函数将被调用两次。 Now I want to know, how can I call that function once and store the result in a variable, then parse that variable? 现在,我想知道如何调用该函数一次并将结果存储在变量中,然后解析该变量?
You can simply place your query in a subquery and consume the value returned by the function in the outer query: 您可以简单地将查询放在子查询中,并在外部查询中使用该函数返回的值:
SELECT SUBSTRING_INDEX(sr,',', 1) AS s,
SUBSTRING_INDEX(sr,',', -1) AS r
FROM (
SELECT calculate_both_score_and_reputation(u.id) AS sr
FROM users u) AS t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.