views:

62

answers:

3
CREATE TABLE jokecategory (
  jokeid INT NOT NULL,
  categoryid INT NOT NULL,
  PRIMARY KEY (jokeid, categoryid)
) DEFAULT CHARACTER SET utf8;

especially PRIMARY KEY (jokeid, categoryid)? or is there a better way to write this?

Thank you in advance;-)

+4  A: 

Yes it is a perfectly good table and primary key (I might call this an "association" table, but I would not call it a "lookup" table).

Some people (not I) would insist on having a surrogate key column jokecategoryid as the primary key; if you do that you still need a UNIQUE constraint on (jokeid, categoryid) to enforce the business rule.

Tony Andrews
I agree -- make your keys whichever way you like. The utility of each method is related to the nature of the problem itself in my opinion. Sometimes it is easier to use multiple columns, especially when using a framework that generates code and forms and tables for you.
MJB
@Tony Andrews thank you for that!I think this is what confused me "Some people (not I) would insist on having a surrogate key column jokecategoryid as the primary key". if i was to have this surrogate key column, why would i have it? what are the benefits over the above?
Imran
I see no benefits in adding a surrogate key. Some people like surrogates for (foolish?) consistency; others use them because they use a "framework" (see MJB's comment) that tends to chuck a surrogate into every table.
Tony Andrews
Agreed, a surrogate key is usually not required. I've seen them useful in cases where we need a FK to refer to the join table multiple times - so instead of having jokeid+categoryid everywhere, we just have a jokecategoryid. OTOH, sometimes it's better to have FKs use the "natural" key, especially if it's never intended to be updated.
Jeffrey Kemp
A: 

I would expect the table to have two foreign keys e.g.

CREATE TABLE jokecategory (
  jokeid INT NOT NULL REFERENCES joke (jokeid), 
  categoryid INT NOT NULL REFERENCES category (categoryid), 
  PRIMARY KEY (jokeid, categoryid)
) DEFAULT CHARACTER SET utf8;
onedaywhen
A: 

Yes, it is a perfectly good table, as Tony has already pointed out. But I see no need to create it as a regular heap table with a primary key index. That's two storage structures. Just the index structure would do, so my advice is to create this table as an index organized table.

Here is a link to the documentation: http://download.oracle.com/docs/cd/E11882_01/server.112/e10713/indexiot.htm#CNCPT911

Regards, Rob.

Rob van Wijk