Mysql's primary single-column primary key and composite primary key

Mysql primary key

Storage engine (innodb): For the innodb storage engine, a table must have a primary key.

1. Single column primary key
Create a table:

create table t17(
        id int primary key,
        name char(16)
    )

Insert data into the table:

insert into t17 values
(1,'egon'),
(2,'elex')

Run, the insertion is successful, let's look at the following table:
Insert picture description here
Insert another piece of data:

insert into t17 values(2,'elx')

Run-error:
Insert picture description here
because id has set the primary key, it already exists (similar to unique here).

Note: If you create a table in this way, the table will also be displayed as primary

create table t18(
    id int not null unique,
    name char(16)
    )

If no id is set, continue to insert data:

insert into t17(name) values('wxx')

Run and view the data:
Insert picture description here
Run once, and the id whose name is'wxx' is 0, but the second time it runs, an error will be reported because it already exists:
Insert picture description here

2. Composite primary key The
unique combination of composite primary key and unique is very similar, let's take a look below.

Create a table:

create table t19(
	ip char(16),
    port int,
    primary key(ip,PORT)
    )

Enter the insert statement to insert data into the table:

insert into t19 values('192.168.11.10',80),('192.168.11.10',80)

Operation-Error:
Insert picture description here
Because the two inserted contents are the same, an error will be reported. Let's modify the following:

insert into t19 values('192.168.11.10',80),('192.168.11.10',81)

The operation is successful, let's look at the following table:
Insert picture description here
here the two ports are different and the operation is successful. If the ip is different and the port is the same, it can also run successfully. Anyway, at most one of the two can be the same, which is very similar to the united one.

Guess you like

Origin blog.csdn.net/m0_50481455/article/details/114147193