Supabase函数返回类型报错:如何设置返回类型实现搜索排序?
解决Supabase函数返回类型不匹配问题
你遇到的报错是因为函数声明返回helper表的结构,但实际查询返回的结果比原表多了一个priority列,结构不匹配导致的。
问题原因
原函数的查询语句返回的是helper表的所有字段,再额外添加了priority整数字段,而returns setof helper要求返回结果的结构必须和helper表完全一致,因此触发结构不匹配的错误。
两种解决方法
方法一:自定义复合类型
先创建一个包含原表所有字段和priority字段的复合类型:
create type helper_search_result as ( id text, title varchar, tags varchar, author_name varchar, profile_pic varchar, created_at timestamp with time zone, priority integer );
然后将函数的返回类型改为这个自定义类型:
create or replace function hello(si text) returns setof helper_search_result as $$ begin return query select *, 1 as "priority" from helper where to_tsvector(title) @@ to_tsquery(si) union select *, 0 as "priority" from helper where to_tsvector(tags) @@ to_tsquery(si) order by "priority" desc; end; $$ language plpgsql;
方法二:直接用table(...)指定返回结构
无需提前创建类型,直接在returns子句里定义完整的返回结构:
create or replace function hello(si text) returns table( id text, title varchar, tags varchar, author_name varchar, profile_pic varchar, created_at timestamp with time zone, priority integer ) as $$ begin return query select *, 1 as "priority" from helper where to_tsvector(title) @@ to_tsquery(si) union select *, 0 as "priority" from helper where to_tsvector(tags) @@ to_tsquery(si) order by "priority" desc; end; $$ language plpgsql;
额外提示
如果希望保留同时匹配标题和标签的重复记录(即同一行既出现在标题匹配结果,又出现在标签匹配结果),可以把union替换为union all——union会自动去重,而union all会保留所有结果。
内容的提问来源于stack exchange,提问作者ABHILESH SINGH
相关产品推荐
相关产品推荐

