views:

55

answers:

3

Hi all,

I'm trying to find the most efficient way to do something and would appreciate your advice!

I have a table with the following columns:

id
category
category_sequence
other_columns

id is an auto-increment column and the primary key. The category is selected by the user on the UI.

What I'd like to do is generate a category_sequence, which is the highest existing category_sequence for that category + 1.

For example, inserting a few rows would like like:

  • 1, 1, 1
  • 2, 1, 2
  • 3, 2, 1
  • 4, 1, 3

and so on.

Obviously I could run a query to extract the highest category_sequence, add one to it, and then run my insert statement. But is there a much more efficient way (some of the inserts will be in fairly big loops, so anything to speed it up, and prevent crossover, would be great).

Thanks in advance, Kev

A: 

Assuming you have a "Category" table to which category refers to, you could have a next_sequence field on there. Then have an insert trigger on your table that pulls the next sequence number, puts it into the category_sequence column, and increments the next_sequence field (would have to all be done in a single transaction).

Eric Petroelje
Hadn't thought of that as an option - thanks for your input.
websushi
+1  A: 

you can try

    insert into mytable
    select "categoryselected",coalesce(max(category_sequence),0)+1 from mytable where category = "categoryselected"

You might have to wrap it in a case statement as well in the case that it is the first record for that category. I don't have mysql to test it on

Gratzy
Great - this worked a treat for me! The coalesce function returns 0 if it is the first row, so no case statement required.Thanks for your help!
websushi
A: 

You can have the database do it by changing your auto_increment field to be category_sequence, then make your primary key category+category_sequence. You can then drop the id field since it's not going to do what you wanted it to. MySql will then increment the category_sequence field exactly the way you describe.

Brent Baisley
Thanks for the response. Unfortunately the 'id' field is needed for other system functions though.
websushi