postgresql - Postgresql 并使用基于同一表中现有记录的数据填充表
问题描述
有一个模式表,它具有不同的属性 link、name、antoherAtrr。
链接,名称- 字符串值和唯一性
任务是查询表中所有现有的行并将它们乘以N个条目,并将它们同时插入到同一个表中,以便链接、名称字段具有唯一值(例如,添加到这些字段中的现有值+字符串中的随机数)
insert into modes (link, name , antoherAtrr)
select * from modes
此代码将给出错误,因为违反了前 2 列的唯一性。
- 模式
create table if not exists modes
(
link varchar,
name varchar,
"anotherAtrr" integer
);
alter table modes owner to postgres;
create unique index if not exists modes_link_uindex
on modes (link);
create unique index if not exists modes_name_uindex
on modes (name);
而不是必须
N是我希望在单个查询中获得的行数(即基于可用行的重复行,但考虑到某些属性的唯一性)
谁对如何写这个有任何想法?你能提供代码解释吗?
解决方案
您可以加入 generate_series 表达式。
一步一步...
创建一个返回 n 行的表表达式,其中包含一个整数字段:
SELECT * FROM generate_series(0,4) AS ser(nr);
nr
----
0
1
2
3
4
(5 rows)
模式包含:
SELECT * FROM modes;
link | name | anotherAtrr
------+------+-------------
foo | bar | 42
(1 row)
从现有表中选择所有内容并将其与生成的数据交叉连接 ( JOIN on true
):
SELECT *
FROM modes
JOIN generate_series(0,4) AS ser(nr) ON true;
link | name | anotherAtrr | nr
------+------+-------------+----
foo | bar | 42 | 0
foo | bar | 42 | 1
foo | bar | 42 | 2
foo | bar | 42 | 3
foo | bar | 42 | 4
(5 rows)
现在通过将数字连接到字符串值来组合字段:
INSERT INTO modes (link, name , "anotherAtrr")
SELECT t1.link ||'_'||ser.nr, t1.name||'_'||ser.nr , t1."anotherAtrr"
FROM modes t1
JOIN generate_series(0,4) AS ser(nr)ON true;
也可以写成:
WITH ser AS (
SELECT * FROM generate_series(0,4) AS nr
)
INSERT INTO modes (link, name , "anotherAtrr")
SELECT t1.link ||'_'||ser.nr, t1.name||'_'||ser.nr , t1."anotherAtrr"
FROM modes t1
JOIN ser ON true;
不相关:
双引号标识符产生的问题多于解决的问题。
推荐阅读
- javascript - My php code suddenly can't work in javascript code
- postgresql - Optimise With Query in PostgreSQL
- java - Add Custom Headers for request in dofilter at Gateway level
- ios - tableview section header is not sticky in multi sectional tableview
- html - 如何更改 gmail 设置以查看促销选项卡中的注释?
- javascript - 我的反应 CSSTransition 动画不起作用
- hibernate - 通过 JDBC 语句插入 hibernate_sequence 值(1)”:org.hibernate.tool.schema.spi.CommandAcceptanceException:执行 DDL 时出错“
- python-3.x - Jupyter notebook Pandas Dataframe 访问不起作用
- excel - 查找文本并更改颜色
- python - django rest框架中的异步