MYSQL: Two fields as PRIMARY KEYs + 1 Field as UNIQUE, a question

耗尽温柔 提交于 2019-12-12 19:14:12

问题


I have two primary (composite) keys that refer to a shop and a branch. I thought I should have used a corresponding ID for each row, so I added a UNIQUE + AUTO_INCREMENT named ID.

So I had on the table a column named ID (AUTO INCREMENT), but it was declared PRIMARY - which was done automatically, and I don't want the ID to be PRIMARY. Just the shop and branch.

I have learnt how to trick MYSQL to accept the ID field as UNIQUE and AUTO INCREMENT, as it was not extremely trivial to make the AUTO_INCREMENT (it wanted to make it PRIMARY). I had to ERASE the ID Field (for some reason it didn't let me erase its PRIMARY index), then declare it INDEX, and only then AUTO INCREMENT.

Is that a good approach ? Could there be something I am doing wrong going with this design ?

Thanks !!!


回答1:


The prevailing wisdom is that every table should have a unique autonumbered column named Id.

In classical data modeling, as developed by Codd and Date, the ID field is not necessary for a complete logical model of the data.

What good does the ID field do you? Do you ever reference a row in this table by its ID? If never, then just leave the field out. (shop, branch) provided a perfectly good candidate to be the PK.




回答2:


What did your create table statement look like? Because I imagine this:

CREATE TABLE foo (
    IDCol int not null auto_increment,
    shop int not null,
    branch int not null,

    /* ... */

    UNIQUE KEY IDCol (IDCol),
    PRIMARY KEY (shop, branch)
);


来源:https://stackoverflow.com/questions/6494276/mysql-two-fields-as-primary-keys-1-field-as-unique-a-question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!