Retrieving the index of an inserted row

后端 未结 3 495
野的像风
野的像风 2021-01-16 13:27

I\'m trying to keep the database tables for a project I\'m working on nice and normalized, but I\'ve run into a problem. I\'m trying to figure out how I can insert a row int

3条回答
  •  佛祖请我去吃肉
    2021-01-16 13:55

    The general solution to this is to do one of two things:

    1. Create a procedural query that does the insert and then retrieves the last inserted id (using, ie. LAST_INSERT_ID()) and returns it as output from the query.

    2. Do the insert, do another insert where the id value is something like (select myid from table where somecolumnval='val')

    2b. Or make the select explicit and standalone, and then do the other inserts using that value.

    The disadvantage to the first is that you have to write a proc for each of these cases. The disadvantage to the second is that some db engines don't accept that, and it clutters your code, and can be slow if you have to do a where on multiple columns.

    This assumes that there may be inserts between your calls that you have no control over. If you have explicit control, one of the other solutions above is probably better.

提交回复
热议问题