search
HomeDatabaseMysql TutorialThe difference between union primary key and composite primary key

1. Composite primary key

#The so-called composite primary key means that the primary key of your table contains more than one field. If it is not used, it has no business meaning. The auto-incrementing id is used as the primary key.

For example:

create table test 
( 
   name varchar(19), 
   id number, 
   value varchar(10), 
   primary key (name,id) 
)

The combination of the name and id fields above is the composite primary key of your test table. It appears because your name field may have the same name, so you need to add The ID field can ensure the uniqueness of your record. Generally, the field length and number of fields of the primary key should be as small as possible.

There will be a doubt here? The primary key is the only index, so why can a table create multiple primary keys?

In fact, "the primary key is the only index" is a bit ambiguous. For example, we create an ID field in the table, grow it automatically, and set it as the primary key. This is no problem because "the primary key is the only index" and the ID field automatically grows to ensure uniqueness, so it is OK.

At this point, we create another field name with type varchar and set it as the primary key. You will find that you can fill in the same name value in multiple rows of the table. Isn’t this illegal? Is this sentence "the primary key is the only index"?

That's why I said "the primary key is the only index" is ambiguous. It should be "When there is only one primary key in the table, it is the only index; when there are multiple primary keys in the table, it is called a composite primary key, The combination of composite primary keys guarantees a unique index".

Why self-increasing ID can already be used as the primary key for unique identification, why is a composite primary key still needed? Because not all tables must have the ID field. For example, if we build a student table and there is no ID that uniquely identifies the student, what should we do? The student's name, age, and class may all be repeated, and a single field cannot be used to Unique identification. At this time, we can set multiple fields as primary keys to form a composite primary key. These multiple fields jointly identify uniqueness. Among them, there is no problem if certain primary key field values ​​are repeated, as long as there are not multiple records. If all primary key values ​​are exactly the same, they are not considered duplicates.

2. Joint primary key

Joint primary key, as the name suggests, is the combination of multiple primary keys to form a primary key combination (the primary key is in principle unique , don’t be troubled by unique values.)

The meaning of the joint primary key: use 2 fields (or multiple fields, specifically a combination of 2 fields will be used later) to determine a record, indicating that these 2 fields The fields are not unique. The two fields can be repeated separately. The advantage of this setting is that you can intuitively see the number of records of a repeated field.

A simple example:

Primary key A and primary key B form a joint primary key

The data of primary key A and primary key B can be exactly the same. The union lies in primary key A and primary key B. The resulting joint primary key is unique.
In the following example, the data of primary key A is 1, the data of primary key B is also 1, and the combined primary key is actually 11. This 11 is a unique value, and the unique value of 11 is absolutely not allowed to appear again. (This is a many-to-many relationship)

Primary key A data Primary key B data
1  1   ##2   2
3  3

The joint primary key of primary key A and primary key B The maximum value is

11

12
13
21
22
23
31
32
33

Summary : From my point of view, a composite primary key consists of more than one field, such as ID name, ID phone, etc., while a joint primary key must be a combination of the themes of two tables at the same time. This is the biggest difference from the composite primary key!

For more related questions, please visit the PHP Chinese website:

mysql video tutorial

The above is the detailed content of The difference between union primary key and composite primary key. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
How does MySQL handle concurrency compared to other RDBMS?How does MySQL handle concurrency compared to other RDBMS?Apr 29, 2025 am 12:44 AM

MySQLhandlesconcurrencyusingamixofrow-levelandtable-levellocking,primarilythroughInnoDB'srow-levellocking.ComparedtootherRDBMS,MySQL'sapproachisefficientformanyusecasesbutmayfacechallengeswithdeadlocksandlacksadvancedfeatureslikePostgreSQL'sSerializa

How does MySQL handle transactions compared to other relational databases?How does MySQL handle transactions compared to other relational databases?Apr 29, 2025 am 12:37 AM

MySQLhandlestransactionseffectivelyusingtheInnoDBengine,supportingACIDpropertiessimilartoPostgreSQLandOracle.1)MySQLusesREPEATABLEREADasthedefaultisolationlevel,whichcanbeadjustedtoREADCOMMITTEDforhigh-trafficscenarios.2)Itoptimizesperformancewithabu

How does MySQL differ from PostgreSQL?How does MySQL differ from PostgreSQL?Apr 29, 2025 am 12:23 AM

MySQLisbetterforspeedandsimplicity,suitableforwebapplications;PostgreSQLexcelsincomplexdatascenarioswithrobustfeatures.MySQLisidealforquickprojectsandread-heavytasks,whilePostgreSQLispreferredforapplicationsrequiringstrictdataintegrityandadvancedSQLf

How does MySQL handle data replication?How does MySQL handle data replication?Apr 28, 2025 am 12:25 AM

MySQL processes data replication through three modes: asynchronous, semi-synchronous and group replication. 1) Asynchronous replication performance is high but data may be lost. 2) Semi-synchronous replication improves data security but increases latency. 3) Group replication supports multi-master replication and failover, suitable for high availability requirements.

How can you use the EXPLAIN statement to analyze query performance?How can you use the EXPLAIN statement to analyze query performance?Apr 28, 2025 am 12:24 AM

The EXPLAIN statement can be used to analyze and improve SQL query performance. 1. Execute the EXPLAIN statement to view the query plan. 2. Analyze the output results, pay attention to access type, index usage and JOIN order. 3. Create or adjust indexes based on the analysis results, optimize JOIN operations, and avoid full table scanning to improve query efficiency.

How do you back up and restore a MySQL database?How do you back up and restore a MySQL database?Apr 28, 2025 am 12:23 AM

Using mysqldump for logical backup and MySQLEnterpriseBackup for hot backup are effective ways to back up MySQL databases. 1. Use mysqldump to back up the database: mysqldump-uroot-pmydatabase>mydatabase_backup.sql. 2. Use MySQLEnterpriseBackup for hot backup: mysqlbackup--user=root-password=password--backup-dir=/path/to/backupbackup. When recovering, use the corresponding life

What are some common causes of slow queries in MySQL?What are some common causes of slow queries in MySQL?Apr 28, 2025 am 12:18 AM

The main reasons for slow MySQL query include missing or improper use of indexes, query complexity, excessive data volume and insufficient hardware resources. Optimization suggestions include: 1. Create appropriate indexes; 2. Optimize query statements; 3. Use table partitioning technology; 4. Appropriately upgrade hardware.

What are views in MySQL?What are views in MySQL?Apr 28, 2025 am 12:04 AM

MySQL view is a virtual table based on SQL query results and does not store data. 1) Views simplify complex queries, 2) Enhance data security, and 3) Maintain data consistency. Views are stored queries in databases that can be used like tables, but data is generated dynamically.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.