Get the App
SLTechnology News&Howtos  ›  Database  › 

The method of adding compound Primary key to mysql

Shulou Source: shulou.com Published: 2022-06-01 03:26:13 09月18日 Update

How to add compound primary key to mysql? This problem may be often seen in our daily study or work. I hope you can gain a lot from this question. The following is the reference content that the editor brings to you, let's take a look at it!

A primary key constraint defines a primary key in a table to uniquely determine the identifier of each row of data in the table. A primary key can be a column or a combination of multiple columns in a table, where a primary key composed of multiple columns is called a compound primary key.

The compound primary key cannot contain unnecessary redundant columns. When a column of a compound primary key is deleted, if the primary key formed by the remaining columns still satisfies the uniqueness principle, then the compound primary key is incorrect. This is the principle of minimization.

How do I add a compound primary key?

You can add a compound primary key when you create a table, where the primary key is composed of multiple fields, and the syntax rules are as follows:

PRIMARY KEY [Field 1, Field 2, … , field n]

Example: create a data table tb_emp, assuming that there is no primary key id in the table. In order to uniquely identify an employee, you can combine name and deptId as the primary key.

Mysql > CREATE TABLE tb_emp-> (- > name VARCHAR (25),-> deptId INT (11),-> salary FLOAT,-> PRIMARY KEY (id,deptId)->); Query OK, 0 rows affected (0.37 sec) mysql > DESC tb_emp +-+-+ | Field | Type | Null | Key | Default | Extra | + -+ | name | varchar (25) | NO | PRI | NULL | deptId | int (11) | NO | PRI | NULL | | salary | float | YES | | NULL | | +-+-+ 3 rows in Set (0.14 sec) Thank you for your reading! After reading the above, do you have a general idea of how to add compound primary keys to mysql? I hope the content of the article will be helpful to all of you. If you want to know more about the relevant articles, you are welcome to follow the industry information channel.

Tags: Content fields methods principles data articles questions combinations unions minimum one line employees uniqueness multiple datasheets more identifiers regulations see Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Linux MariaDB Shulou Tech Info Docker