如何在 MySQL 中压平 table 值函数的结果?
How to flatten results from table-valued function in MySQL?
我正在使用 MySQL,我有一个函数可以接受来自 table 行的 col 数据,以及 return 一个 table 值函数。例如,像这样的函数:
CREATE FUNCTION [dbo].[wordlongerthan4](
@input text
) returns @result table(
pos int,
word varchar,
)
这将 return 长于 4char 的单词及其位置。
我想做一个sql像下面这样的事情
select t.name,wordlongerthan4(t.content) from sometable as t;
在 table
------------------------------------------------------------------
| id | name | content |
------------------------------------------------------------------
|1 | my1 | i love something and nothing |
|2 | my2 | It is a sunny day today |
得到结果:
|name | pos | word |
--------------------------------
|my1 |8 |something |
|my1 |22 |nothing |
|my2 |9 |sunny |
|my2 |20 |today |
我怎么写sql?(函数wordlongerthan4已经有了,我只需要sql!)
你说的是:
- 遍历每条记录并提取内容。
- 通过分隔符拆分内容(space,在本例中)。
- 测量每个部分的长度
- 将零件添加到成功结果数组中,它的长度 < n
(4).
- 返回零件,以及来自
记录它最初的来源。
正如 ajreal 所说,这是最好在应用层完成的事情,大概是在您的 php/java/whatever 内部。
目前没有内置字符串 explode/split 函数,但这里的这个问题可能有用:Equivalent of explode() to work with strings in mysql.
您可以(ab)使用 MySQL 8 中的新 JSON_TABLE 函数来执行此操作:
set @input = 'i love something and nothing';
SELECT Value, LENGTH(Value) as Length, LOCATE(Value, @delimited) as pos
FROM
JSON_TABLE(
CONCAT('["', REPLACE(@delimited, ' ', '", "'), '"]'),
"$[*]"
COLUMNS(
Value varchar(50) PATH "$"
)
) data
where LENGTH(Value) > 4;
我正在使用 MySQL,我有一个函数可以接受来自 table 行的 col 数据,以及 return 一个 table 值函数。例如,像这样的函数:
CREATE FUNCTION [dbo].[wordlongerthan4](
@input text
) returns @result table(
pos int,
word varchar,
)
这将 return 长于 4char 的单词及其位置。
我想做一个sql像下面这样的事情
select t.name,wordlongerthan4(t.content) from sometable as t;
在 table
------------------------------------------------------------------
| id | name | content |
------------------------------------------------------------------
|1 | my1 | i love something and nothing |
|2 | my2 | It is a sunny day today |
得到结果:
|name | pos | word |
--------------------------------
|my1 |8 |something |
|my1 |22 |nothing |
|my2 |9 |sunny |
|my2 |20 |today |
我怎么写sql?(函数wordlongerthan4已经有了,我只需要sql!)
你说的是:
- 遍历每条记录并提取内容。
- 通过分隔符拆分内容(space,在本例中)。
- 测量每个部分的长度
- 将零件添加到成功结果数组中,它的长度 < n (4).
- 返回零件,以及来自 记录它最初的来源。
正如 ajreal 所说,这是最好在应用层完成的事情,大概是在您的 php/java/whatever 内部。
目前没有内置字符串 explode/split 函数,但这里的这个问题可能有用:Equivalent of explode() to work with strings in mysql.
您可以(ab)使用 MySQL 8 中的新 JSON_TABLE 函数来执行此操作:
set @input = 'i love something and nothing';
SELECT Value, LENGTH(Value) as Length, LOCATE(Value, @delimited) as pos
FROM
JSON_TABLE(
CONCAT('["', REPLACE(@delimited, ' ', '", "'), '"]'),
"$[*]"
COLUMNS(
Value varchar(50) PATH "$"
)
) data
where LENGTH(Value) > 4;