[英]CREATE TABLE AS with PRIMARY KEY in one statement (PostgreSQL)
Is there a way to set the PRIMARY KEY in a single "CREATE TABLE AS" statement?有没有办法在单个“CREATE TABLE AS”语句中设置 PRIMARY KEY?
Example - I would like the following to be written in 1 statement rather than 2:示例 - 我希望将以下内容写在 1 个语句而不是 2 个语句中:
CREATE TABLE "new_table_name" AS SELECT a.uniquekey, a.some_value + b.some_value FROM "table_a" AS a, "table_b" AS b WHERE a.uniquekey=b.uniquekey;
ALTER TABLE "new_table_name" ADD PRIMARY KEY (uniquekey);
Is there a better way of doing this in general (assume there are more than 2 tables, eg 10)?通常有没有更好的方法(假设有 2 个以上的表,例如 10 个)?
According to the manual: create table and create table as you can either:根据手册: create table和create table你可以:
But not both create table as with primary key - what you wanted.但不是都像主键一样创建表——你想要的。
If you want to create a new table with the same table structure of another table, you can do this in one statement (both creating a new table and setting the primary key) like this:如果你想创建一个与另一个表具有相同表结构的新表,你可以在一个语句中执行此操作(同时创建一个新表并设置主键),如下所示:
CREATE TABLE mytable_clone (
LIKE mytable
INCLUDING defaults
INCLUDING constraints
INCLUDING indexes
);
No, there is no shorter way to create the table and the primary key.不,没有更短的方法来创建表和主键。
See the command below, it will create a new table with all the constraints and with no data.请参阅下面的命令,它将创建一个包含所有约束且没有数据的新表。 Worked in postgres 9.5
在 postgres 9.5 工作
CREATE TABLE IF NOT EXISTS <ClonedTableName>(like <OriginalTableName> including all)
well in mysql,both is possible in one command在 mysql 中,两者都可以在一个命令中实现
the command is命令是
create table new_tbl (PRIMARY KEY(`id`)) as select * from old_tbl;
where id
is column with primary key of old_tbl其中
id
是主键为 old_tbl 的列
done...完毕...
You may do this way你可以这样做
CREATE TABLE IOT (EMPID,ID,Name, CONSTRAINT PK PRIMARY KEY( ID,EMPID))
ORGANIZATION INDEX NOLOGGING COMPRESS 1 PARALLEL 4
AS SELECT 1 as empid,2 id,'XYZ' Name FROM dual;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.