Copy a table and define the primary key.

huangapple go评论88阅读模式
英文:

Copy a table and define the primary key

问题

我有一个使用.to_sql方法生成的名为temp_element的表格。我想要复制它,并将列id_element定义为主键。

CREATE TABLE element AS
SELECT * FROM temp_element,
PRIMARY KEY (id_element);

这不起作用。为什么?我正在使用SQLite,所以无法在之后使用ALTER TABLE来定义主键。

英文:

I have a table temp_element generated with .to_sql (method of Pandas). I want to copy it and define column id_element as the primary key.

CREATE TABLE element AS
SELECT * FROM temp_element,
PRIMARY KEY id_element;

This doesn't work. Why? I'm using SQLite so can't use ALTER TABLE to define primary keys afterwards.

答案1

得分: 1

使用Sqlite似乎不可能实现这一点。

如果您的表已经存在并且希望稍后添加主键,您不能使用ALTER TABLE语句来创建主键。相反,您必须创建一个带有主键的新表,并将数据复制到这个新表中。

您需要创建带有主键的表,然后将数据插入其中。

INSERT INTO element SELECT * FROM temp_element;

英文:

With Sqlite this doesn't seem to be possible.

https://www.techonthenet.com/sqlite/primary_keys.php#:%7E:text=The%20syntax%20to%20add%20a,pk_col1%2C%20pk_col2%2C%20

> If your table already exists and you wish to add a primary key later, you can not use the ALTER TABLE statement to create a primary key. Instead, you must create a new table with the primary key and copy the data into this new table.

You'd have to create the table with its primary key, then insert the data into it.

INSERT INTO element SELECT * FROM temp_element;

huangapple
  • 本文由 发表于 2023年6月29日 21:27:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76581515.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定