How to insert data without specifying a value for a primary key with non-invasive growth?

I have this table:

CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)


1. insert into persons values (1, 'John', 'Smith', 'LA', 'LA');
2. insert into persons (p_id, lastname, firstname, address, city) values  (2, 'John', 'Smith', 'LV', 'LV');

How to insert data into a table without specifying a value for the primary key (the primary key does not have the auto_increment attribute).

I tried:

  • insert in the values ​​of the faces ("John", "Smith", "LA", "LA");
  • insert into the values ​​of faces (null, 'John', 'Smith', 'LA', 'LA');
  • paste in the values ​​of faces (auto, "John", "Smith", "LA", "LA");

but no luck

+3
source share
4 answers

I saw it implemented as

  • DEFAULT value in PK column (e.g. -9999)
  • A table containing the value of Current_PK
  • INSERT, PK -9999 Current_PK Current_PK

, , - MAX .

, , .

, PK.

0

, , MySQL , ? ID (, MAX (P_Id) 1 ), .

, , , - :

INSERT INTO Persons (P_Id, FirstName, LastName, Address, City)
VALUES ((SELECT MAX(P_Id) + 1 FROM Persons), 'John', 'Smith', 'LA', 'LA');

, , MySQL, .

+6
 Select p_id+1 From Person OrderBy p_id desc limit 1;
0

, , . , UNIQUE, , . .

I am very curious to find out why someone wants to use the primary key without using auto-increment. Auto increment provides the most elegant way to avoid duplicate data in any table. If the rest of the data is identical to another row in this table, it can be identified and committed / deleted. Used in combination with another row, which is a unique key (to catch any duplicates), the table becomes very reliable.

ianm

0
source

Source: https://habr.com/ru/post/1722738/


All Articles