我不知道如何輕松解釋我需要做什么,但我會嘗試。
假設我有一個有 5 個用戶的用戶表。
id name
1 Steve
2 Pat
3 Robin
4 Carl
5 Sarah
而不是僅僅做一個select * from users我需要做這個不同的和更困難的。
我需要構建一個查詢,為用戶表中的每一行運行一個帶有引數(名稱)的查詢,然后給我相同的輸出select * from users
我知道這聽起來很奇怪,但這是我真正需要做的..
所以我想要發生的是:
我需要遍歷用戶表以找出有多少行。(5) - 這是我想要執行查詢的次數。
對于查詢的每次執行,我需要在 where 子句中更改名稱。第一次執行 = Steve,第二次 = Pat,依此類推。
最后,我只想要一個輸出,所有的東西都在一起,所以我需要合并結果。
如果我手動執行此操作,它將如下所示:
Select id, name from users where name = 'Steve'
union all
Select id, name from users where name = 'Pat'
union all
Select id, name from users where name = 'Robin'
union all
Select id, name from users where name = 'Carl'
union all
Select id, name from users where name = 'Sarah'
在我的真實情況下,我需要單獨的查詢,所以這樣in ('Steve', 'Pat')的解決方案將不起作用。
我希望您了解我在尋找什么,如果您有任何問題,請提出。我正在使用 postgres v.10
uj5u.com熱心網友回復:
這應該可以按您的意愿作業。
DO $$
DECLARE
var_req TEXT;
rec_key record;
cur_key CURSOR FOR SELECT distinct name from users;
BEGIN
open cur_key;
loop
fetch cur_key into rec_key;
EXIT WHEN NOT FOUND;
var_req := '
insert into your_output_table
select id, name from users
where name = '''||rec_key.name||'''
;
';
execute var_req;
end loop;
close cur_key;
END $$;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/439919.html
標籤:sql PostgreSQL 循环 参数
上一篇:向量子集的Rlapply回圈性能
