Two column as a primary keys in mysql?

前端 未结 8 1705
孤独总比滥情好
孤独总比滥情好 2020-12-15 06:34

Today I found out you can have a primary key using two columns (tsql). The PK must be unique but both columns do not (the combo must be unique).

I thought that was v

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-15 06:41

    Yes, this is a normal thing to do in SQL and it works (having a composite primary key, in which multiple fields together constitute a unique value).

    Two notes:

    1. Make sure it's necessary. It often is and then it's fine. But sometimes it's a sign that you further need to normalize your data model.

    2. I'm thinking that you don't want to make and a b be foreign keys from another table and then make them the composite primary key of your table. What happens if you set up a cascading delete, in which one user id, but not the other is deleted? So the composite primary key is fine, but then you don't want come from "unrelated" foreign keys.

提交回复
热议问题