MYSQL--Unique uniqueness Constraint

Source: Internet
Author: User

3. UNIQUE constraint

Constraints uniquely identify each record in a database table.

Create a test table:

CREATE TABLE' test '. ' Info ' (' id ' )INT( One) UNSIGNED not NULLauto_increment, ' Idcard 'VARCHAR( -)UNIQUE  not NULL, ---Add the unique constraint ' mobile ' directly on the fieldVARCHAR( One),  PRIMARY KEY(' id ')) ENGINE=INNODB CHARSET=UTF8 COLLATE=Utf8_estonian_ci;

Add UNIQUE constraint unique:

/*In addition to the above method of adding a unique constraint, if you need to name a unique constraint and define a unique constraint for more than one column, write the following: The Uc_idcard constraint is a unique constraint that is synthesized by the mobile and idcard groups. */CREATE TABLE' test '. ' Info ' (' id ' )INT( One) UNSIGNED not NULLauto_increment, ' Idcard 'VARCHAR( -)UNIQUE, ' mobile 'VARCHAR( One),  PRIMARY KEY(' id '),CONSTRAINTUc_idcardUNIQUE(Mobile,idcard)) ENGINE=INNODB CHARSET=UTF8 COLLATE=Utf8_estonian_ci; If a unique constraint is added in the presence of a table
--no-name constraintALTER TABLE' Info 'ADD UNIQUE(' Idcard ');
--uc_idcard constraints synthetic unique constraints by mobile and Idcard groupsALTER TABLE' Info 'ADD CONSTRAINTUc_idcardUNIQUE(Mobile,idcard);

Revoke a UNIQUE constraint

-- remove a constraint from a specified field ALTER TABLE DROP INDEX  --  Remove the name constraint ALTERTABLEDROPINDEX

To add data to a UNIQUE constraint:

--add a basic dataINSERT  into' Info ' (' Idcard ', ' mobile ')VALUES('99999','1111');--Add a idcard duplicate recordINSERT  into' Info ' (' Idcard ', ' mobile ')VALUES('99999','2222'); Result: Error code:1062DUPLICATE Entry'99999'  for KEY 'Idcard';--add NULL in a unique constraintINSERT  into' Info ' (' Idcard ', ' mobile ')VALUES(NULL,'1111');--add null againINSERT  into' Info ' (' Idcard ', ' mobile ')VALUES(NULL,'2222'); Result: ID Idcard mobile-------------------------     6(NULL)1111         7(NULL)2222
Reason: Because null ! = null

MYSQL--Unique uniqueness Constraint

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.