简体   繁体   English

PostgreSQL 随机化外键

[英]PostgreSQL randomize foreign key

I have 2 tables in Postgres ( inventory table and event table ).我在 Postgres 中有 2 个表(库存表事件表)。 In the inventory table my primary key consist of 8 strings.在库存表中,我的主键由 8 个字符串组成。 Example '03163161'.示例“03163161”。

Now I have to input them in the Event table randomly with the primary key that is on the inventory table.现在我必须使用库存表上的主键将它们随机输入到事件表中。

In what way can I do it?我可以通过什么方式做到这一点? I've tried googling it but no one seems to have a solution on it and I'm trying to experiment on how i can random input the PK of inventory table to the event table since the data is almost 3k.我试过用谷歌搜索它,但似乎没有人有解决方案,我正在尝试尝试如何将库存表的 PK 随机输入到事件表中,因为数据几乎是 3k。

Update#1更新#1

I've tried using the code below我试过使用下面的代码

INSERT INTO dashboard.event(terminal_id) VALUES (SELECT terminal_id FROM dashboard.inventory)

but i get the error:但我收到错误:

ERROR:  syntax error at or near "SELECT"
LINE 1: INSERT INTO dashboard.event(terminal_id) VALUES (SELECT term...
                                                         ^
SQL state: 42601
Character: 50

Don't use the keyword VALUES with a select in the insert.不要将关键字 VALUES 与插入中的选择一起使用。 See this question:看到这个问题:

Update or Insert (multiple rows and columns) from subquery in PostgreSQL 从 PostgreSQL 中的子查询更新或插入(多行和多列)

INSERT INTO dashboard.event(terminal_id) 
SELECT terminal_id 
FROM dashboard.inventory --should work

I think you want the 'references' keyword.我认为您需要“引用”关键字。 For example:例如:

https://www.postgresql.org/docs/current/ddl-constraints.htmlhttps://www.postgresql.org/docs/current/ddl-constraints.html

create table inventory
(
 id INTEGER NOT NULL UNIQUE,
 ... other fields
);

create table events
(
 eid INTEGER REFERENCES inventory(id),
 ... other fields
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM