postgresql - 插入唯一的随机值,没有在 PostgreSQL 中定义的任何约束
问题描述
我想在第一个循环中生成唯一的随机客户 id 值,所以它检查 i 的值是否小于 0.2,如果 i 值 > 0.2,它将 Null 添加到该行,那么它应该添加一个不应该的唯一随机值以前出现在该列中。我不想对此列使用 UNIQUE 或 PK 约束,因为我想向它添加多个 Null 值,这也不是 PK。我需要一个有效的方法。这是我迄今为止所做的事情,但未能实现我想要的。我是 PostgreSQL 新手,所以请帮帮我。谢谢。
CREATE OR REPLACE FUNCTION aa_dev.rand_cust(low INT ,high INT)
RETURNS TABLE (Cust_id int) AS
$$
declare
i int := 0;
counter int := 0;
rand int := 0;
begin
DROP TABLE IF EXISTS aa_dev.Customer;
CREATE TABLE IF NOT EXISTS aa_dev.Customer (
Cust_id INT
);
while counter <= high loop
rand = floor(random()* (high-low + 1) + low);
i = random()* (1-0 + 1) + 0;
if i > 0.2 then
Insert into aa_dev.Customer (Cust_id) values(rand);
IF (EXISTS(SELECT rand_cust.Cust_id FROM aa_dev.Customer WHERE rand_cust.Cust_id = rand)) THEN
UPDATE aa_dev.Customer SET rand_cust.Cust_id = floor(random()* (high-low +1) + low) WHERE rand_cust.Cust_id = rand;
END IF;
-- Insert into aa_dev.Customer (Cust_id) values(floor(random()* (high-low + 1) + low))
else
Insert into aa_dev.Customer (Cust_id) values(Null);
end if;
counter := counter + 1;
end loop;
return query
select *
from aa_dev.Customer;
end
$$
LANGUAGE plpgsql;
select * from aa_dev.rand_cust(1, 50);
解决方案
推荐阅读
- angular - 如何更改表中值的格式?
- flutter - Flutter 是否支持 Google Assistant Read It 功能?
- maven - Kotlin maven 插件内部依赖
- python - 将数据转换为列表
- javascript - TS2488:键入“字符串 | null' 必须有一个返回迭代器的 '[Symbol.iterator]()' 方法
- odoo - 如何添加按钮或链接以重定向到树视图 odoo 12 内的另一个模型?
- rust - 混合未来的执行者
- rest - 分层 REST API 与规范化 REST API
- python - 随机森林输出
- sql - mssql 2012 中的 group_concat 和 distinct