U
U
ukoHka2018-03-15 12:58:52
MySQL
ukoHka, 2018-03-15 12:58:52

How to insert id of current record into another column in Mysql?

There is a table of objects in which there are fields id (PRIMARY, AUTO_INCREMENT) and related_to (relationship).
By default, each object must refer to itself (so that when choosing the main object, you can get all the objects related to it, including itself).
I found an example of a BEFORE INSERT trigger on the Internet:

IF NEW.related_to = 0 THEN
    SET NEW.related_to = last_insert_id()+1 ;
  END IF

But this code always sets related_to to 1, i.e. last_insert_id() returns 0. I read that this may be due to the fact that with each request a new connection is created and last_insert_id is set to zero, but using a persistent connection is not recommended, and also not solves problems when objects are added by different people with different connections (each will have its own last_insert_id counter).
Although maybe I misunderstand and a permanent connection is created for the scripts themselves, in which case the problem should seem to be solved, but something strange happens to me and the left id is inserted (id of records inserted into other tables at the same time as this record)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2018-03-15
@ukoHka

I am confused by the attitude towards myself - it will surely cause endless cycles. And I don't understand why it would be necessary. There is a suspicion of a fundamentally wrong approach to the organization of the database and relationships.
But in order to be able to add your id to the newly created record, there is an afterSave method in the model www.yiiframework.com/doc-2.0/yii-db-baseactivereco...
last_insert_id()+1 - this is the path to failure
. Is it one to one, one to many, or many to many? If many to many, then there should be a separate table where dependencies are stored.

R
RidgeA, 2018-03-15
@RidgeA

c last_insert_id can be a problem with concurrent queries
Maybe it's better to use an after insert trigger ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question