简体   繁体   English

根据另一个字段使一个字段唯一

[英]Make one field unique depending on another field

I have the following MySQL table.. 我有以下MySQL表..

userid - foreign key
date   - primary key
slot1  - 1st free slot
slot2  - 2nd free slot
slot3  - 3rd free slot
slot4  - 4th free slot
slot5  - 5th free slot
slot6  - 6th free slot
slot7  - 7th free slot
slot8  - 8th free slot

All the slots are for the same day, so the user can input different times of the day that he is free. 所有的插槽都在同一天,因此用户可以输入他空闲的一天中的不同时间。

Now I did this and it worked and now I stumbled upon a problem. 现在我做了这个并且它有效,现在我偶然发现了一个问题。 I entered some data for one user and now when I try to enter data for another user for the same date I cant because it says it already exists. 我为一个用户输入了一些数据,现在当我尝试为同一日期输入另一个用户的数据时,我不能说它已经存在了。

How do i make it so that I can have the same user enter multiple dates and also another user enters the same date?... But the same user can't enter the same date twice... How can this be done? 我如何制作它以便我可以让同一个用户输入多个日期而另一个用户输入相同的日期?...但是同一个用户不能两次输入相同的日期...如何做到这一点?

You may want to use a composite PRIMARY KEY on user_id and date . 您可能希望在user_iddate上使用复合PRIMARY KEY

You may also use a unique key as Quassnoi suggested , but it really looks like your date field alone is not a valid candidate for a primary key . 您也可以使用Quassnoi建议唯一密钥 ,但实际上看起来您的date字段不是主键的有效候选者

ALTER TABLE mytable ADD CONSTRAINT ux_mytable_user_date UNIQUE KEY (user, date)

You should drop you PRIMARY KEY on date . 你应该在date放弃PRIMARY KEY

You may either create one on user_id, date (as Daniel Vassallo suggested), or, if you need to reference this table, create a surrogate PRIMARY KEY (say, with an AUTO_INCREMENT column). 您可以在user_id, date上创建一个(如Daniel Vassallo建议的那样),或者,如果需要引用此表,则创建一个代理PRIMARY KEY (例如,使用AUTO_INCREMENT列)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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