Skip to main content
Inspiring
June 9, 2010
Question

INSERT order and getting row ID back

  • June 9, 2010
  • 2 replies
  • 2330 views

I've been over to the MySQL site just to confirm this, but any voice of experience would be nice here...

So I'm reaching the point that when an order is placed I do two things:

1. Insert a row into table 'orders'

2. Insert shopping cart rows for that order, into the 'ordered_items'  table

The problem I have is, table 'orders' uses an auto increment value for each row's key field, so I need some way to insert the row and retrieve that newly generated key field value.

MySQL provides this:

INSERT INTO foo (auto,text)
    VALUES(NULL,'text');         # generate ID by inserting NULL
INSERT INTO foo2 (id,text)
    VALUES(LAST_INSERT_ID(),'text');  # use ID in second table

Does this seem OK ?

In theory I don't *need* to use an auto increment field. For example I could use the user's unique_session_ref and concatenate a datetime onto it ? I wasn't sure if such a VARCHAR type field for the key would impact performance.

Let me know what you think ?

This topic has been closed for replies.

2 replies

Inspiring
June 9, 2010

You could use a uuid instead of an autoincrement.

Inspiring
June 9, 2010

Is UUID unique enough for the orders table key field ?

Isn't it a 35 character string, and therefore an impact on performance if made a key field ?

Inspiring
June 9, 2010

If you are concerned with uniqueness, you could always run a select query first.  Opinions vary as to whether this is necessary.

For performance, it shouldn't make any appreciable difference.

June 9, 2010

I think this seems to be ok, but additionaly you have to implement the LAST_INSERT_ID() function. With MSSQL this is much easier. There you can either use the result attribute from cfquery tag (and get the IDENTITYCOL value) or directly insert a "select @@identity" clause after the insert statement, but in the same cfquery tag (maybe the "select @@identity" statement could also be used in MySQL).

And yes, if you use a varchar as primary key this can cause an impact of performance. Auto-increment values are normally integers, this data type uses less memory then varchar and the comparison methods for integers and varchars (to match foreign keys) differ significant.

Inspiring
June 9, 2010

So are you saying I can't use that LAST_INSERT_ID() in the cfquery ?

June 9, 2010

Dax,

you can use the LAST_INSERT_ID() function, but I think you have to additionally implement it.

I don't know much about MySQL. Is LAST_INSERT_ID() an internal MySQL function?