A method that makes two fields different in MySQL

Source: Internet
Author: User

Sometimes we encounter such a situation: there are a number of different majors, each major has some different school numbers, professional + students can correspond to individual. At this time, how to define the column in the database, to ensure that the Professional + student number corresponding to the uniqueness of students?

It is obviously not feasible to define the number as a unique (unique) because there are 1000 such a number in both A and B majors.

Method 1: Federated primary Key

PRIMARY KEY (Major,id);

not recommended . Because the federated primary key will cause inconvenience to the maintenance of the table. In addition, the primary key may have been set.

Method 2: Establish a federated unique constraint (Federated unique Index) ( recommended )

Federated UNIQUE Constraints: (the uniqueness index is automatically created when a uniqueness constraint is created)

ALTER TABLE ADD CONSTRAINT UNIQUE (Major,id);

Federated Unique Indexes:

CREATE UNIQUE INDEX  on student (Major,id);

The difference between the two:

① when inserting 20 data into a database, where 5 data repeats, if a uniqueness constraint is used, the result must be that 20 of the data are all rejected for insertion. If a unique index is used, if the Ignore duplicates switch is turned on, 15 data that is not duplicated are inserted correctly and 5 duplicate data is ignored.

② If a column has multiple row values that are NULL, you cannot establish a unique index on that column.

A method that makes two fields different in MySQL

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.