[英]How do I see the primary key of a table? And how can I add multiple primary keys?
I have the following table: https://i.imgur.com/gWyCQxS.png我有下表: https : //i.imgur.com/gWyCQxS.png
db name: testdb
table name: testtable
I purposely did not create any primary keys when creating the table because I wanted to learn how to it afterwards.我在创建表时故意没有创建任何主键,因为我想在之后学习如何使用它。
I used the following to add a primary key:我使用以下内容添加主键:
ALTER TABLE testtable
ADD PRIMARY KEY (column2);
In pgAdmin, I can see that it worked: https://i.imgur.com/3wKsOLo.png在 pgAdmin 中,我可以看到它有效: https : //i.imgur.com/3wKsOLo.png
I tried to do the same for column1
but I got this error: ERROR: multiple primary keys for table "testtable" are not allowed SQL state: 42P16
我尝试对
column1
执行相同操作,但出现此错误: ERROR: multiple primary keys for table "testtable" are not allowed SQL state: 42P16
Q1: Why am I not allowed to have multiple primary keys for this table and how can I add multiple ones? Q1:为什么这个表不允许有多个主键,如何添加多个主键?
Also, without using the pgAdmin GUI , I'm trying to see what the current primary key is for testtable
.另外,在不使用 pgAdmin GUI 的情况下,我试图查看
testtable
的当前主键是什么。 I found a thread here on Stackoverflow that recommended the following code:我在 Stackoverflow 上找到了一个推荐以下代码的线程:
select OBJECT_NAME(OBJECT_ID) AS NameofConstraint
FROM sys.objects
where OBJECT_NAME(parent_object_id)='testtable'
and type_desc LIKE '%CONSTRAINT'
I get an error after executing this: ERROR: relation "sys.objects" does not exist
.执行此操作后出现错误:
ERROR: relation "sys.objects" does not exist
。
Q2: How can I view all of the primary keys using psql or without using the pgAdmin GUI? Q2:如何使用 psql 或不使用 pgAdmin GUI 查看所有主键?
A1: Try to use a composite KEY like this: A1:尝试使用这样的复合 KEY:
ALTER TABLE testtable
ADD PRIMARY KEY (column1,column2);
A2: (Q2: How can I view all of the primary keys using psql?) A2: (Q2:如何使用 psql 查看所有主键?)
Something like this:像这样的东西:
select tc.table_schema, tc.table_name, kc.column_name
from information_schema.table_constraints tc
join information_schema.key_column_usage kc
on kc.table_name = tc.table_name and kc.table_schema = tc.table_schema and kc.constraint_name = tc.constraint_name
where tc.constraint_type = 'PRIMARY KEY'
and kc.ordinal_position is not null
order by tc.table_schema,
tc.table_name,
kc.position_in_unique_constraint;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.