开发者

MySQL Set NULLABLE Unique Field

开发者 https://www.devze.com 2023-01-20 07:30 出处:网络
I\'ve a case where I need to store twitter username, email, and some other field to be unique. However开发者_JAVA技巧, I can only set twitter username later. Not on registration process. How can I han

I've a case where I need to store twitter username, email, and some other field to be unique. However开发者_JAVA技巧, I can only set twitter username later. Not on registration process. How can I handle this in SQL?

Here's my current SQL structure:

CREATE TABLE `kios_users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `username` varchar(32) NOT NULL,
 `password` varchar(60) NOT NULL,
 `email` varchar(100) NOT NULL,
 `no_hp` varchar(15) NOT NULL,
 `twitter_oauth_token` varchar(60) NOT NULL,
 `twitter_oauth_token_secret` varchar(60) NOT NULL,
 `twitter_username` varchar(32) NULL,
 `verify_level` enum('just_reg','hp_ok','all_ok') NOT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `email` (`email`),
 UNIQUE KEY `no_hp` (`no_hp`),
 UNIQUE KEY `username` (`username`),
 UNIQUE KEY `twitter_username` (`twitter_username`)
) ENGINE=MyISAM

With this kind of structure, I can't set twitter_username to empty. Can you suggest me the best table structure?


You could set a dummy unique value, but is not the best. You could manage uniqueness in the app logic, not the best. I think the best is to use another table with only two fields: id and twitter_username with a unique key on twitter_username and insert only when you have the twitter username. Also, there should be a one-to-one relationship on both id columns.


You've set twitter_username to be "NOT NULL". Try

`twitter_username` varchar(32) NULL


Could you not just allow NULL for your twitter params and enforce uniqueness at the application level? (ie. in php/.net/whatever you're using)

Alternatively, store the twitter account details in a separate table linked to your user id

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号