سؤال

Currently I have this table in my database:

CREATE TABLE `twMCUserDB` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `mc_userName` text NOT NULL,
  `mc_userPass` text NOT NULL,
  `tw_userName` text NOT NULL,
  `tw_userPass` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

I want the column mc_userName to be unique too (just like id), but mc_userName must be a string.

I tried to make it also a primary key, but that didn’t work.

When I add data to the table, do I first have to check whether the mc_userName already exists? Or is there any built-in function in MySQL that I can use (in the insert query, or somewhere else)?

هل كانت مفيدة؟

المحلول

just add UNIQUE

`mc_userName` text NOT NULL UNIQUE,

or

CREATE TABLE `twMCUserDB` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `mc_userName` text NOT NULL,
  `mc_userPass` text NOT NULL,
  `tw_userName` text NOT NULL,
  `tw_userPass` text NOT NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT tb_uq UNIQUE (mc_userName)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

نصائح أخرى

Why don't you make 'mc_userName ' the Primary Key instead of id? You will have to change the data type of mc_userName to VARCHAR as described in this post: MySQL error: key specification without a key length. Alternatively, create a composite primary key containing id and username.

If you can't do this because of the design of the database then use the EXISTS keyword in a query. Have a look here for more information: http://dev.mysql.com/doc/refman/5.0/en/exists-and-not-exists-subqueries.html

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top