gpt4 book ai didi

postgresql - 无法单独获取所有列值,而是获取一列中的所有值 postgresql --9.5

转载 作者:行者123 更新时间:2023-11-29 13:22:19 25 4
gpt4 key购买 nike

CREATE OR REPLACE FUNCTION public.get_locations(
location_word varchar(50)
)
RETURNS TABLE
(
country varchar(50),
city varchar(50)
)
AS $$
DECLARE
location_word_ varchar(50);
BEGIN
location_word_:=concat(location_word, '%');
RETURN QUERY EXECUTE format(' (SELECT c.country, ''''::varchar(50) as city FROM webuser.country c
WHERE lower(c.country) LIKE %L LIMIT 1)
UNION
(SELECT c.country,ci.city FROM webuser.country c
JOIN webuser.city ci ON c.country_id=ci.country_id
WHERE lower(ci.city) LIKE %L LIMIT 4)',
location_word_,
location_word_ ) ;

END
$$ language PLPGSQL STABLE;

SELECT public.get_locations('a'::varchar(50));

我明白了;

+get_locations   +
+record +
------------------
+(Andorra,"") +
+(Germany,Aach) +
+(Germany,Aalen) +
+(Germany,Achim) +
+(Germany,Adenau)+

如何像下面这样逐列放置/获取值?因为否则我无法正确匹配这些值。我应该逐列获取国家和城市等值。

|country         | city       |
-------------------------------
| Andorra | "" |
| Germany | Aach |
| Germany | Aalen |
| Germany | Achim |
| Germany | Adenau |

最佳答案

您的函数被声明为返回表,因此您必须像使用表一样使用它:

SELECT *
FROM public.get_locations('a'::varchar(50));

不相关,但是:

您的函数太复杂了,您不需要动态 SQL,也不需要 PL/pgSQL 函数。

您可以将其简化为:

CREATE OR REPLACE FUNCTION public.get_locations(p_location_word varchar(50)) 
RETURNS TABLE(country varchar(50), city varchar(50))
AS $$
(SELECT c.country, ''::varchar(50) as city
FROM webuser.country c
WHERE lower(c.country) LIKE concat(p_location_word, '%')
LIMIT 1)
UNION ALL
(SELECT c.country ,ci.city
FROM webuser.country c
JOIN webuser.city ci ON c.country_id = ci.country_id
WHERE lower(ci.city) LIKE concat(p_location_word, '%')
LIMIT 4)
$$
language SQL;

关于postgresql - 无法单独获取所有列值,而是获取一列中的所有值 postgresql --9.5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39510231/

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