"select * into new_table from old_table" 不创建主键

"select * into new_table from old_table" does not create primary key

我使用 sql 查询来动态创建表,所以我做了 StockSample 并且我想克隆它的结构但是这样它不会将默认 id 作为主键并自动递增它

这是我的代码,

    cursor = connection.cursor()
    query= "select * into stock_"+str(stock_id)+" from stocksample where 1=2;"
    cursor.execute(query)

以上内容 SQL 查询创建:

股票样本:

型号:

class StockSample(models.Model):
    user_id = models.ForeignKey(AppUser,on_delete=models.CASCADE)
    product_name = models.CharField(max_length=100)
    product_id = models.ForeignKey(Product,on_delete=models.CASCADE)
    barcode = models.CharField(max_length=100, null=True, blank=True)
    mrp = models.IntegerField()
    selling_price = models.IntegerField()
    expiry_date = models.DateField(null=True, blank=True)

试过了,但仍然没有将 id 作为主键:

  1. query = "Select *, id = ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) Into stock_"+str(stock_id)+" From stocksample Where 1 = 2"
  2. query2 = "alter table stock_"+str(stock_id)+" add primary key id" GIVES ERROR

select ... into new_table(或首选的、符合标准的 create table new_table as select ....)确实只复制 数据,而不是真正的结构。

如果要克隆 table 的结构,包括约束(例如主键),请使用

create table stocksample_xxx (like stocksample  including indexes);

including indexes 将复制所有索引定义,同时重新创建主键。不过,没有 复制主键的选项。

如果您还想复制“自动递增”列的定义,您需要放弃旧的 serial 列以支持 recommended identity 列,那么您可以使用 including indexes including identity.