简体   繁体   中英

Foreign Key : Unique & part of Composite Primary Key

I have the tables:

( coupon )

| id |    name  |    description   |     start_at       |       end_at        |
| 1  | coupon_1 | FREE coupon ...  |2017-02-01 04:00:33 | 2017-02-15 04:00:33 |

( coupon_code )

| id | coupon_id |    code   |
| 1  |    1      | P69MFE5K  |
| 13 |    1      | 75PRUE4G  |

( coupon_recipient )

| coupon_id | user_id | couponcode_id |
|    1      |    4    |      1        |
|    1      |    4    |      13       |

The coupon_recipient Keys:

coupon_id, user_id, couponcode_id = Composite Primary Key

couponcode_id = Unique Index

Is it ok to have couponcode_id as part of composite primary key & unique index ?

Because a User can receive the same coupon multiple times with different coupon_code ( Composite Primary Key )

The same coupon_code can only be used 1 time ( Unique Index )

There is no technical reason you can't have couponcode_id as the unique index and as part of the primary key. However, I don't see any practical reason to use coupon_id & user_id in the PK as it just makes the table key wider, which can negatively affect performance.

Assuming your Primary Key is also the clustered index key, if couponcode_id is unique in coupon_recipient, why not just use that as the primary key. You could than create a Non-clustered index for the coupon_id & user_id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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