英文:
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.
> 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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论