tags:

views:

30

answers:

1

I have a table Course and every Course has many Resources.

Course
==========
course_id

Resource
==========
course_id
number

I want something like a separate autoincrement for each course_id. Or, in other words, I want to auto-enumerate the resources for a given course. For example, the resource table could look something like:

course_id | number
==================
1         | 1
1         | 2
2         | 1
1         | 3
1         | 4
2         | 2
2         | 3

and so on. I want to do this in SQL, using IBM DB2.

A: 

You should let Resource pick its own ids...

resource_id | course_id
=======================
1           | 1
2           | 1
3           | 2
4           | 1
5           | 1
6           | 2
7           | 2

...and discover the rank via queries:

SELECT course_id,
       (SELECT COUNT(*)
          FROM Resource
         WHERE resource_id < r.resource_id
       ) + 1 AS rank
  FROM Resource r

This is undoubtedly more work for the optimiser, but will simplify life dramatically in every other respect (e.g., handling deletions).

Marcelo Cantos
To make it easier, when reading the table, how about an insert trigger that set's the course_id based on 'select max (number)+1 from Resource where course_id=<course_id of inserted item>' I am not sure if you can do this operation if you have a key over Course_id and number, but you can always go with the resource_id too.
Peter Schuetze