请看一下:
SELECT calculate_both_score_and_reputation(u.id) AS sr FROM users u
它返回如下内容:
+----------+
| sr |
+----------+
| 0,1322 |
| 3, 232 |
| -2, 9978 |
| 31, 5745 |
+----------+
现在我想将该函数的结果拆分为两个不同的列:
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
结果如下:
+----+------+
| s | r |
+----+------+
| 0 | 1322 |
| 3 | 232 |
| -2 | 9978 |
| 31 | 5745 |
+----+------+
结果如预期。但是如你所见,该函数将被调用两次。现在我想知道,如何调用该函数一次并将结果存储在变量中,然后解析该变量?
答案 0 :(得分:1)
您可以简单地将查询放在子查询中,并使用外部查询中函数返回的值:
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