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)?
The syntax for creating a unique constraint using an ALTER TABLE statement in MySQL is: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n); table_name.
MySQL – Distinct Values To get unique or distinct values of a column in MySQL Table, use the following SQL Query. SELECT DISTINCT(column_name) FROM your_table_name; You can select distinct values for one or more columns. The column names has to be separated with comma.
The UNIQUE constraint ensures that all values in a column are different. Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns.
Luckily, MySQL provides another kind of index called UNIQUE index that allows you to enforce the uniqueness of values in one or more columns. Unlike the PRIMARY KEY index, you can have more than one UNIQUE index per table.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With