SQL炼金术复合键Ord

2024-03-29 11:06:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建表单的复合主键(date,id)。我的代码目前看起来有点像这样

class Gyroinfo(Base):
    __tablename__ = 'GYROINFO'

    id = Column(Integer, primary_key=True,autoincrement = True)
    date = Column(DateTime, primary_key = True)

但这默认为表单的主键(id,date)。如何切换主键顺序?在


Tags: key代码idtrue表单basedatecolumn
1条回答
网友
1楼 · 发布于 2024-03-29 11:06:35

我假设你在这里使用MySQL,如果不告诉我,我会删除这个答案。在

您可以阅读mikebayer关于用MySQL here重新排序主键字段的内容。为什么SQLAlchemy的行为是这样的,here。在

您可以通过在id字段上使用PrimaryKeyConstraint和一个单独的UniqueConstraint来实现您想要的。E、 g.:

class Gyroinfo(Base):
    __tablename__ = 'GYROINFO'

    id = Column(Integer, autoincrement=True, unique=True)
    date = Column(DateTime)

    __table_args__ = (
        PrimaryKeyConstraint(date, id),
    )

它生成以下sql:

^{pr2}$

id字段定义中没有额外的unique=True,SQLAlchemy会发出一个CREATE TABLE,列的顺序如您所愿:

CREATE TABLE `GYROINFO` (
        id INTEGER NOT NULL AUTO_INCREMENT,
        date DATETIME NOT NULL,
        PRIMARY KEY (date, id)
)

但被MySQL拒绝:

Incorrect table definition; there can be only one auto column and it must be defined as a key

但是,它回避了一个问题:为什么您需要在主键中使用date字段。由于id是自动递增的,它在表中的所有条目中都是唯一的,因此在包含{}的复合字段中包含{}不会增加额外的复杂性。我会坚持:

class Gyroinfo(Base):
    __tablename__ = 'GYROINFO'

    id = Column(Integer, autoincrement=True, primary_key=True)
    date = Column(DateTime, index=True)

相关问题 更多 >