【问题标题】:"select * into new_table from old_table" does not create primary key“select * into new_table from old_table”不创建主键
【发布时间】:2021-12-22 19:26:05
【问题描述】:

我使用 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

【问题讨论】:

  • 你想在那里实现什么?看起来您正在滚动自己的分区实现。为什么不简单地使用内置分区?

标签: sql django postgresql django-models


【解决方案1】:

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

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

create table stocksample_xxx (like stocksample  including indexes);

including indexes 将复制所有索引定义,这也会重新创建主键。没有选项可以复制主键。

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

【讨论】:

  • including indexes including identity 没有进行自动增量。 “抛弃旧的连续专栏”是什么意思?我该怎么做。
  • 您的原始表需要有一个定义为identity 的列(例如integer generated always as identity)才能使including identity 工作。如果您使用serial 定义“自动增量”列,则不会被复制。
  • 谢谢人.. (like stocksample INCLUDING ALL); 为我工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-11
  • 1970-01-01
  • 1970-01-01
  • 2022-08-02
  • 2013-03-08
  • 1970-01-01
  • 2012-07-14
相关资源
最近更新 更多