Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composite key as foreign key (sql)

here are my two tables of concern:

CREATE TABLE IF NOT EXISTS `tutorial` (   `beggingTime` time NOT NULL,   `day` varchar(8) NOT NULL,   `tutorId` int(3) NOT NULL,   `maxMembers` int(2) NOT NULL,   `minMembers` int(1) NOT NULL,   PRIMARY KEY (`beggingTime`,`day`,`tutorId`),   KEY `tutorId` (`tutorId`) )    CREATE TABLE IF NOT EXISTS `group` (   `groupId` tinyint(3) NOT NULL AUTO_INCREMENT,   `status` varchar(20) NOT NULL,   `groupName` varchar(50) NOT NULL,   PRIMARY KEY (`groupId`) )  

I would like to create a field in 'group' that would link to the composite unique keys in 'tutorial'. So I guess my question is, how do I relate these tables? do I have to to create foreign keys field in 'group' for each primary key in 'tutorial'?

like image 278
dgamma3 Avatar asked Mar 20 '12 01:03

dgamma3


People also ask

Can a composite key be a foreign key?

A composite key specifies multiple columns for a primary-key or foreign-key constraint. The next example creates two tables. The first table has a composite key that acts as a primary key, and the second table has a composite key that acts as a foreign key.

How do I add a composite key to a foreign key in SQL?

You can create a composite foreign key just as you would create a single foreign key, except that instead of specifying just one column, you provide the name of two or more columns, separated by a comma.

Can a composite key be a primary key?

Composite Key Declaration When over one column or field in a table are combined to achieve the task of uniquely identifying row values, then that composite key can be either a primary or a candidate key of that table.

Does MySQL support composite foreign key?

MySQL supports foreign keys, which permit cross-referencing related data across tables, and foreign key constraints, which help keep the related data consistent.


1 Answers

Per the mySQL documentation you should be able to set up a foreign key mapping to composites, which will require you to create the multiple columns.

Add the columns and put this in your group table

FOREIGN KEY (`beggingTime`,`day`,`tutorId`)      REFERENCES tutorial(`beggingTime`,`day`,`tutorId`) 

As Steven has alluded to in the below comments, you SHOULD try to re-architect this so that the tutorial table uses an actual primary key (even if it is just an identity surrogate key). This will allow for greater performance as SQL was built for this type of relationship, not composite.

like image 149
Justin Pihony Avatar answered Sep 25 '22 20:09

Justin Pihony