Get all inserted IDs when inserting multiple rows using a single query

前端 未结 7 1030
误落风尘
误落风尘 2021-01-17 11:40

I\'ve already looked at other answers and I still feel that my question is relevant and deserves a separate entry.

I have a table named settings(which stores user se

7条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-17 11:47

    I did this for a bit though did not find the data useful in the end so stopped.

    I track the datetime and user_who_altered of each entry into the table so retrieving the list becomes simple.

    It is important to set a variable with the time however, rather than relying on NOW():

      INSERT INTO table (username,privelege,whenadded,whoadded) VALUES ('1','2','$thetime','$theinserter'),('1','5','$thetime','$theinserter'),etc...;
    

    will insert the multiple rows nicely.

    to retrieve the array you seek:

    SELECT idrow FROM table WHERE username='1' AND whenadded='$thetime' AND whoadded='$theinserter';
    

    This is good practice as you are able to track which user modified the record and it does not depend on locks or chance.

    As for your own solution, it will work and saves a query. I would worry about how it might respond to prepared statements on a busy table though and perhaps the method used ought to consider that. The method I use is immune to such problems.

提交回复
热议问题