Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will Sqlalchemy automatically create index for foreign key?

I use MyISAM engine in MYSQL. I find that the foreign keys in the table has been automatically created indexes. Is the behavior of Sqlalchemy or MYSQL? I don't need the index for the foreign key. What should I do? Add the param index=False when defining the column?

My code:

class A(Base):
    __tablename__ = "a"
    a_id = Column(BigInteger, primary_key=True, autoincrement=True)

class B(Base):
    __tablename__ = "b"
    b_id = Column(BigInteger, primary_key=True, autoincrement=True)
    a_id = Column(BigInteger, ForeignKey(A.a_id))

I found the index for a_id in B has been created automatically. Is it correct? Can I do this if I want to remove such an index?

class B(Base):
    __tablename__ = "b"
    b_id = Column(BigInteger, primary_key=True, autoincrement=True)
    a_id = Column(BigInteger, ForeignKey(A.a_id), index=False)
like image 261
flypen Avatar asked Dec 19 '25 18:12

flypen


1 Answers

Lafada, you are incorrect. KEY a_id (a_id) in table b clearly shows an index was made on the foreign key field. This is a behaviour of InnoDB -- it will automatically create an index over fields in a foreign key relationship if such an index does not already exist:

http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html

like image 127
joinfu Avatar answered Dec 22 '25 09:12

joinfu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!