Insert an automatic increment of the Primary Key into another table (to join it later)

I am new to MySQL and hope everything works out well. I created a database with 3 tables with columns as shown below (PK Primary Keys):

Users table

  • uid (PK)
  • Username

Directories table

  • UID
  • way
  • Project

DirInfo table

  • infoID (PK)
  • the size
  • dateofcheck
  • exists
  • pathID

When I insert NULL values ​​in Directories.pathID, I get a new path identifier (auto increment). How can I insert the same path identifier in DirInfo.pathID?

I need to run multiple queries in INSERT and SELECT so that each column in each table is updated, or I'm doing something wrong.

+3
source share
1 answer

LAST_INSERT_ID() , INSERT. , .

INSERT INTO Directories (pathId) VALUES (NULL); -- auto-increment
INSERT INTO DirInfo (pathId) VALUES ( LAST_INSERT_ID() );

MySQL, .

INSERT INTO Directories (pathId) VALUES (NULL); -- auto-increment
SET @pathId := LAST_INSERT_ID();
INSERT INTO DirInfo (pathId) VALUES ( @pathId );
+5

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


All Articles