Mysql foreign key by non unique key — how is that possible?

后端 未结 4 1945
南笙
南笙 2021-01-12 08:50

I was migrating mysql database to postgres and stumbled across the following block in DDL (Note: This is what I got from mysqldump):

CREATE TABLE `catalog_pr         


        
相关标签:
4条回答
  • 2021-01-12 09:26

    The most likely answer is that id really is unique in the catalog_propery_value table, but that the author declared the PK to be the superkey (id, sort) for reasons unknown, possibly having to do with indexing, rather than enforcing uniqueness.

    0 讨论(0)
  • 2021-01-12 09:27

    From the manual:

    Deviation from SQL standards: A FOREIGN KEY constraint that references a non-UNIQUE key is not standard SQL. It is an InnoDB extension to standard SQL.

    So it looks like InnoDB allows non-unique indexes as candidates for foreign key references. Elsewhere the manual states that you can reference a subset of columns in the referenced index as long as the referenced columns are listed first and in the same order as the primary key.

    Therefore, this definition is legal in InnoDB, although it's not standard SQL and leaves me, at least, a little confused as to the original designer's intentions.

    Manual page here.

    0 讨论(0)
  • 2021-01-12 09:31

    This is perfectly legal according to wikipedia:

    The columns in the referencing table must be the primary key or other candidate key in the referenced table.

    0 讨论(0)
  • 2021-01-12 09:41

    This weird behavior of FK's in innoDB is described in the manual.

    The handling of foreign key references to nonunique keys or keys that contain NULL values is not well defined for operations such as UPDATE or DELETE CASCADE. You are advised to use foreign keys that reference only UNIQUE and NOT NULL keys.

    PostgreSQL doesn't accept this construction, the foreign key has to point to a unique key.

    0 讨论(0)
提交回复
热议问题