Join Tables and Primary Keys

I have found that many people set up the primary keys for join tables in a manner that I find undesirable. This leaves open the possibility of some sneaky bugs in their programs.

I'll start by covering what I mean by a join table (as opposed to what I will call a data table).

Most basic data is stored in data tables. For example a "users" table is a data table, as is a "groups" table. Each row in a "users" table represents one user, as each row in a "groups" table would represent a group.

[More]

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
I have been known to do this for a single reason, my favorite ORM does not yet allow compound keys (though I know that is coming *very* soon). When not using ORM, I have always done the compound key because it simply makes sense from both a database indexing standpoint and an application standpoint.
# Posted By Brian Rinaldi | 5/24/07 2:42 PM
Without respect to ORM limitations that I'm not familiar with, I've never seen this. I've heard about it, but never experienced it "in the wild". At the very least, this method introduces superfluous data. At the very most, as you illustrated, it's dangerous.
# Posted By Rob wilkerson | 5/24/07 4:52 PM
Brian,

I assume you mean Transfer. Fortunately, Mark said he would be adding support for compound primary keys soon.

Rob,

Agreed. I have actually seen this several times (hence the entry).
# Posted By Steve Bryant | 5/24/07 6:29 PM
yes, after finishing up reading, I was just gonna bring up the ORM issue with compound keys... Good post Steve!


mmh wonder if Active Records supports compound keys...
# Posted By sal | 5/24/07 7:22 PM
If you do need to have the extra id field for ORM (or any other) purposes, you could limit the potential for the kind of bugs mentioned by declaring the two foreign keys as a unique index, i.e.

ALTER TABLE `user2groups` ADD UNIQUE ( `user_id` , `group_id` );
# Posted By TheMeek | 4/16/08 1:31 AM
BlogCFC was created by Raymond Camden. This blog is running version 5.8.001.