简体   繁体   English

关于 sqlalchemy 中的 unique=True 和 (unique=True, index=True)

[英]About unique=True and (unique=True, index=True) in sqlalchemy

When I create tables use flask-sqlalchemy like this:当我创建表时,像这样使用 flask-sqlalchemy:

class Te(Model):
    __tablename__ = 'tt'
    id = Column(db.Integer(), primary_key=True)
    t1 = Column(db.String(80), unique=True, )
    t3 = Column(db.String(80), unique=True, index=True, )

and In my Sequel Pro, I get the table create info:在我的 Sequel Pro 中,我得到了表创建信息:

CREATE TABLE `tt` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `t1` varchar(80) DEFAULT NULL,
  `t3` varchar(80) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `t1` (`t1`),
  UNIQUE KEY `ix_tt_t3` (`t3`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

this means t1 is entirely same as t3 in MySQL?这意味着 t1 与 MySQL 中的 t3 完全相同? So when you define unique=True , it's not require to define index=True ?因此,当您定义unique=True时,不需要定义index=True吗?

Thanks.谢谢。

I think you have a term confusion with the index purpose in sqlalchemy.我认为您对 sqlalchemy 中的索引用途有一个术语混淆。 In sql databases index are used speed up query performance.在 sql 数据库中,索引用于加快查询性能。

According to the sqlalchemy documentation of defining constraints and indexes.根据定义约束和索引的 sqlalchemy 文档。

You would notice the use of the index key because the sql code generated is:您会注意到索引键的使用,因为生成的 sql 代码是:

UNIQUE KEY `ix_tt_t3` (`t3`)

The way how sqlalchemy nouns the index is idx_%columnlabbel . sqlalchemy 命名索引的方式是idx_%columnlabbel And that matches with the sql code generated.这与生成的 sql 代码相匹配。

So the use or not of index it is only related with performance and the unique key means that the column values cannot be repeated all along of the same column in the 'tt' table.所以索引的使用与否只与性能有关,唯一键意味着'tt'表中同一列的列值不能一直重复。

Hope this helps,希望这可以帮助,

It is not required.这不是必需的。 A unique constraint is more often than not implemented using a unique index , but you need not care about that detail, if all you want is uniqueness.唯一约束通常是使用唯一索引实现的,但如果您想要的只是唯一性,则无需关心该细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM