简体   繁体   English

如何在PostgreSQL中插入主/外键行

[英]How to insert a primary/foreign key row in PostgreSQL

I'm populating a database in PostgreSQL for a Newspaper Online. 我正在PostgreSQL中为在线报纸填充数据库。 Now my doubt lies on how to insert a value into a table which only attribute is both a primary and a foreign key. 现在,我的疑问在于如何在只有属性既是主键又是外键的表中插入值。

In this context, the admin is the first person to ever register an account. 在这种情况下,管理员是第一个注册帐户的人。 So idAdmin = idA = 1: 所以idAdmin = idA = 1:

CREATE TABLE AUTENTICADO (
    idA serial NOT NULL ,
    login VARCHAR(45) NOT NULL,
    password VARCHAR(45) NOT NULL,
    email VARCHAR(40) NOT NULL,
    PRIMARY KEY (idA) );

CREATE TABLE ADMIN (
    idAdmin INT  NOT NULL REFERENCES AUTENTICADO (idA),
    PRIMARY KEY (idAdmin) );

It would be logical to insert values into 'ADMIN' as I tried below, although it is obviously not possible considering 'idAdmin' is a primary key (and a foreign key). 如下所述,将值插入“ ADMIN”是合乎逻辑的,尽管考虑到“ idAdmin”是主键(和外键)显然是不可能的。

INSERT INTO AUTENTICADO VALUES ('john','adadfsfsdfs', 'john@random.com')
INSERT INTO ADMIN VALUES (1)

Is there a way to register that the first user to create an account (idA = 1) is the admin (idAdmin = idA = 1) ? 有没有一种方法可以注册第一个创建帐户(idA = 1)的用户是admin(idAdmin = idA = 1)?

although it is obviously not possible considering 'idAdmin' is a primary key (and a foreign key). 尽管显然不可能考虑'idAdmin'是主键(和外键)。

So what? 所以呢?

If you fix the first query to list the columns and use a returning clause to get the auto-generated value for the SERIAL ID, it just works: 如果修复第一个查询以列出列并使用returning子句获取SERIAL ID的自动生成的值,则它可以正常工作:

INSERT INTO AUTENTICADO(login,password,email)
  VALUES ('john','adadfsfsdfs', 'john@random.com')
  returning idA;

Result: 结果:

ida 
-----
   1
(1 row)

Second query: 第二个查询:

insert into admin values(1);
select * from admin;

Result: 结果:

idadmin 
---------
       1

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

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