I have two parent tables, BusinessGroup and SocialGroup, and one child table, Members. A Member can belong to either parent, but not both.
As far as I can see, there are two options for constructing the child table.
Opt 1: Include a field for ParentType, and another for ParentID. The ParentType would be an enum (Business, Social) and the ParentID would be the PK from the respective parent table.
Opt 2: Include a field for BusinessGroupID, and another for SocialGroupID. In this case, the fields would need to be nullable, and only one could contain a value.
Any ideas on which approach is best?
I tried option 1 in MySQL, and created two foreign keys from the child back to the parents. I ran into trouble when inserting values though, since MySQL was expecting a corresponding value in BOTH parent tables.
As a supplementary question: how do things change if I have a larger number of parents, e.g. 6?
Thanks!
CREATE TABLE Group (
GroupID integer NOT NULL
, Name varchar(18)
, Description varchar(18)
, GroupType varchar(4) NOT NULL
-- all columns common to any group type
);
ALTER TABLE Group ADD CONSTRAINT pk_Group PRIMARY KEY (GroupID) ;
CREATE TABLE BusinessGroup (
GroupID integer NOT NULL
-- all columns specific to business groups
);
ALTER TABLE BusinessGroup
ADD CONSTRAINT pk_BusinessGroup PRIMARY KEY (GroupID)
, ADD CONSTRAINT fk1_BusinessGroup FOREIGN KEY (GroupID) REFERENCES Group(GroupID) ;
CREATE TABLE SocialGroup (
GroupID integer NOT NULL
-- all columns specific to social groups
);
ALTER TABLE SocialGroup
ADD CONSTRAINT pk_SocialGroup PRIMARY KEY (GroupID)
, ADD CONSTRAINT fk1_SocialGroup FOREIGN KEY (GroupID) REFERENCES Group(GroupID) ;
CREATE TABLE Person (
PersonID integer NOT NULL
, GroupID integer NOT NULL
);
ALTER TABLE Person
ADD CONSTRAINT pk_Person PRIMARY KEY (PersonID)
, ADD CONSTRAINT fk1_Person FOREIGN KEY (GroupID) REFERENCES Group(GroupID) ;
"parent tables" is probably a misnomer - in the relational model I'd flip your relationship. e.g. make members the master records table, and a join table that allows 1-1 mapping, so have a PK of member_id or whatever the right field is, and map to the FK in either BusinessGroup or SocialGroup.
Related
The tables will build, but every time I try to insert values into the table I get a 1452 error of foreign key constraints fails. I wonder if the problem has to do with EMPLOYEE table has a foreign key for STORE_CODE in the STORE table, and STORE table has a foreign key for EMP_CODE in EMPLOYEE table. Is the circular reference the problem here?
ALTER TABLE EMPLOYEE DROP FOREIGN KEY STORE_CD;
ALTER TABLE STORE DROP FOREIGN KEY REGION_CD;
ALTER TABLE STORE DROP FOREIGN KEY EMPLOYEE_CD;
DROP TABLE IF EXISTS EMPLOYEE, REGION, STORE;
CREATE TABLE EMPLOYEE (
EMP_CODE int NOT NULL PRIMARY KEY,
EMP_TITLE varchar(4),
EMP_LNAME varchar(15),
EMP_FNAME varchar(15),
EMP_INITIAL varchar(1),
EMP_DOB datetime,
STORE_CODE int NOT NULL
) Engine=InnoDB;
-- Table Region
CREATE TABLE REGION (
REGION_CODE int NOT NULL PRIMARY KEY,
REGION_DESCRIPT varchar(20)
) Engine=InnoDB;
-- Table Store
CREATE TABLE STORE (
STORE_CODE int NOT NULL PRIMARY KEY,
STORE_NAME varchar(20) NOT NULL,
STORE_YTD_SALES numeric NOT NULL,
REGION_CODE int NOT NULL,
EMP_CODE int NOT NULL
) Engine=InnoDB;
ALTER TABLE EMPLOYEE ADD CONSTRAINT STORE_CD
FOREIGN KEY STORE_CD(STORE_CODE) REFERENCES STORE(STORE_CODE);
ALTER TABLE STORE ADD CONSTRAINT REGION_CD
FOREIGN KEY REGION_CD(REGION_CODE) REFERENCES REGION(REGION_CODE);
ALTER TABLE STORE ADD CONSTRAINT EMPLOYEE_CD
FOREIGN KEY EMPLOYEE_CD(EMP_CODE) REFERENCES EMPLOYEE(EMP_CODE);
It's not possible to have mutual foreign keys unless you allow at least one of the columns to be NULL. Otherwise you can never have a consistent set of tables: If you add the store first, it will refer to a nonexistent employee; if you add the employee first, it will refer to a nonexistent store.
So you need to allow the referencing column to be NULL. Then you can add a row to the first table with NULL in the referencing column, add a row to the second table, then fill in the referencing column in the first table with the ID from the second table.
In my experience with relational databases, I think you should create an
intermediate table to conect "store" with "employee" (lets name it (store_has_employee) with the atributes(idstore(fk), idemployee(fk) and isManager(boolean)).
Then you should insert the "regions" first, so you can insert a "store", then when you have registered "employees", all you have to do is conect them in "store_has_employee", and if you want to say that is the manager, just insert isManager=true.
This is the most eficient way to do it and to get faster queries.
Hope it helps.
Which one you Want to insert first? If EMPLOYEE then Make STORE_CD (nullable=true) in EMPLOYEE After that Insert STORE item with EMPLOYEE id and Update EMPLOYEE with store code.You can use Transaction for this whole process.
Due to my lack of understanding SQL, the simplest solution for me has been to remove the foreign key from the employee table so that I don't have a circular reference. Then populate the employee table first the other tables afterwards.
i have 3 tables below which have many to many relation...In student table i have multiple foreign keys sec_id,ad_id but i dont know how to add foreign key as parent-child relation please help me out..
CREATE TABLE student(
s_id int AUTO_INCREMENT,
name varchar(30) NOT NULL,
PRIMARY KEY(s_id)
)
CREATE TABLE section(
sec_id int AUTO_INCREMENT,
name varchar(2) NOT NULL,
PRIMARY KEY(sec_id)
)
CREATE TABLE advisor(
ad_id int AUTO_INCREMENT,
name varchar(2) NOT NULL,
PRIMARY KEY(ad_id)
)
If a student can have at most one advisor, then it's a one-to-many relationship.
The normal pattern for implementing that relationship is to define a foreign key column in the child table, the table on the "many" side of the relationship. For example:
ALTER TABLE student ADD ad_id INT COMMENT 'fk ref advisor';
Further, some storage engines, like InnoDB, support and enforce foreign keys. That is, we can have the database enforce restrictions (constraints) on values that can be stored in columns defined as foreign keys.
For example, we can establish a rule that says that a value stored in the ad_id column in the student table... must be found in a row in the advisor table, in the ad_id column.
For example:
ALTER TABLE student ADD CONSTRAINT fk_student_advisor
FOREIGN KEY (ad_id) REFERENCES advisor(ad_id)
ON DELETE RESTRICT ON UPDATE CASCADE
This also enforces a rule that a row from advisor table cannot be deleted if there are rows in student table that reference it.
That same pattern can be repeated for any one to-to-many relationship. For example, if a student can be related to at most one section we can add a foreign key in the same way.
If there's a many-to-many relationship, then we introduce a relationship table that has foreign keys referencing the two related entity tables.
If a student can be related to zero, one or more section, and a section can be related to zero, one or more student, that's an example of a many-to-many relationship.
We can introduce a new table like this (as an example):
CREATE TABLE student_section
( student_id INT NOT NULL COMMENT 'pk, fk ref student'
, section_id INT NOT NULL COMMENT 'pk, fk ref section'
, PRIMARY KEY (student_id, section_id)
, CONSTRAINT fk_student_section_student
FOREIGN KEY student_id REFERENCES student(s_id)
ON DELETE CASCADE ON UPDATE CASCADE
, CONSTRAINT fk_student_section_section
FOREIGN KEY section_id REFERENCES section(sec_id)
ON DELETE CASCADE ON UPDATE CASCADE
)
With that in place, to establish a relationship between a student and a section, we insert a row to the new student_section table. If the student is related to another section, we add another row to the table, referencing the same student, but a different section.
The value stored in the student_id column refers to a row in the student table; and a value stored in the section_id column refers to a row in the section table.
(The many-to-many relationship is really composed of rows in a new table that has a one-to-many relationship to two other tables.)
I have a table created in MySQL (see the code below). As you see in the code I have a foreign key manager which references the idNo. However I only want to reference to employees with the cat='B'. So I need something like
FOREIGN KEY (manager ) REFERENCES Employee(idNo WHERE cat='B').
Any ideas how I can accomplish this.
idNo SMALLINT AUTO_INCREMENT UNIQUE,
name VARCHAR(25) NOT NULL,
telNo INT(11) NOT NULL,
cat CHAR(1) NOT NULL,
manager SMALLINT,
PRIMARY KEY (idNo ),
FOREIGN KEY (manager ) REFERENCES Employee(idNo) on DELETE CASCADE)ENGINE=INNODB
AUTO_INCREMENT=1000;
Foreign keys do not allow conditions.
If you want to force the condition, you must do it via coding.
It can be done inside your non DB code (Java, PHP, VB,...), or you could create a procedure in MySQL that would be called to perform the insert and that will return an error code if condition is not matched.
If you insert from various codes/application, the procedure is the way to go since it would be centralized.
Create a new UNIQUE KEY in Employee combining idNo and cat.
ALTER TABLE Employee ADD UNIQUE KEY (idNo,cat);
Make a foreign key in the child table that references that new unique key.
ALTER TABLE SomeTable ADD FOREIGN KEY (idNo,cat) REFERENCES Employee(idNo,cat);
Then you just need to make sure cat is constrained to the single value 'B' in the child table. One solution is to create a lookup table containing just the single value 'B'.
CREATE TABLE JustB (cat char(1) PRIMARY KEY);
ALTER TABLE SomeTable ADD FOREIGN KEY(cat) REFERENCES JustB(cat);
Now the only value you can use in the child table is 'B', so naturally it can only reference rows in Employee that have a cat of 'B'.
Another solution would be to use a trigger, but I favor the lookup table.
I'm trying to create relationships in MySQL using forein keys. Everytime I successfully create the forien key, but when I describe the table, the key is considered "MUL". After inserting some records into the parent table, I get null values in the child. I've been researching this for hours and have come up empty handed. I even checked the innodb status and have no foreign key error reports. I'm not entirely sure why I'm getting null values, but I'm assuming its because of the "MUL" key value. Can someone confirm this and try and help me out?
create table employee
( id int
, first varchar(128)
, last varchar(128)
, primary key(id)
) engine=innodb;
create table borrow
(ref auto_increment
, empID int
, book varchar(128)
, primary key(ref)
) engine=innodb;
alter table borrow add constraint fk_borrow
foreign key (empID) references employee(id);
insert into borrow (empID, book) values (1,'mike');
The 'MUL' just means that it's not a unique index (i.e. duplicate values are allowed for the KEY). (If it were a unique index, the Key column would show 'UNI'). The FOREIGN KEY constraint doesn't have anything to do with the uniqueness of the foreign key column... it normally is non-unique... a parent can usually have zero, one or more children.
The FOREIGN KEY constraint does not disallow NULL values in the child table. Only a NOT NULL constraint (or a trigger) will do that for you. It's perfectly reasonable for a row in a child table to be an orphan, to not be related to a parent.
When you do the INSERT to the child table, you need to provide a non-NULL value for the foreign key column, if you want that row to reference a row in the parent table.
A foreign key can be defined with an ON DELETE SET NULL clause, but that would only be effective if you were to later delete a parent row that had children related to it. In that case, the child rows would have their foreign key column values set to NULL when the parent row is removed.
Mike said: I'm concerned that the child's foreign key is not getting populated by the parent.
The parent is not responsible for populating the foreign key column of the child. There's an option to have the child's foreign key value updated automatically when the parent's id value is changed... preserving the relationship: ON UPDATE CASCADE. But other than the actions performed by an ON UPDATE or ON DELETE clause, the parent has no responsibility of maintaining the values in a child table.
Mike asked: So how would I get the child's column to be populated from the parent?
You wouldn't. You would first locate (or insert) the row to the parent table. You would then preserve the value of the id column (or the values of whatever columns make up the PRIMARY KEY), and then use that same value for the foreign key column on the child row, when you insert a child row(s).
An error is returned when you set a foreign key to an arbitrary value (a value that does not match an existing PRIMARY KEY value in the parent table. That's the expected behavior.
If you are inserting the child row before the parent, you will need to leave the foreign key column as NULL, and then after you know the id value of the parent, you would then update the child row to set the foreign key column.
create table employee
( id int
, first varchar(128)
, last varchar(128)
, primary key(id) ) engine=innodb;
create table borrow
(ref auto_increment
, empID int
, book varchar(128)
, primary key(ref) ) engine=innodb;
alter table borrow add constraint fk_borrow
foreign key (empID) references employee(id);
insert into employee (id, first, last) values (1, 'foo', 'bar');
insert into borrow (empID, book) values (1,'mike');
insert into borrow (empID, book) values (1,'mulligan');
The two rows added to the borrow table are related to the row in employee, by virtue of the value in the foreign key column (empID) being set to a value that matches an id value in the employee table.
I have Two tables like this:
Table categories:
columns: id, name, parent
1, Foods, 0
2, Drinks, 0
3, FastFood, 1
4, Hamburger, 3
Table documents:
columns: id, name, categoryID
1, CheseBurger, 4
2, shop, 3
the parent column has the parent category's id. So When i want to delete Foods entry from categories, i want to delete all child categories and documents.
How can I do this?
As mentioned before, you could use FOREIGN KEY CONSTRAINTS to achieve such a task. Below would be your new table structure for MySQL to support automatically deleting both documents and child categories:
CREATE TABLE categories (
id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
parent INT(11) UNSIGNED,
INDEX(parent),
FOREIGN KEY (parent) REFERENCES categories(id) ON DELETE CASCADE
) engine=InnoDB;
CREATE TABLE documents (
id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
categoryID INT(11) UNSIGNED NOT NULL,
INDEX(categoryID),
FOREIGN KEY (categoryID) REFERENCES categories(id) ON DELETE CASCADE
) engine=InnoDB;
I would either use a trigger, or create a more detailed "delete" sproc that would handle it.
Some databases support enforcing referential integrity through foreign keys. I've done it with Oracle, but I'm no mysql expert. It's done as an attribute of the foreign key through the keyword 'CASCADE DELETE'. The database automatically handles it for you.
Here's a quick Oracle example:
ALTER TABLE Things ADD CONSTRAINT FK_Things_Stuff
FOREIGN KEY (ThingID) REFERENCES Stuff (ThingID)
ON DELETE CASCADE
;
You have 2 choices - in either case I recommend that you create foreign key constraints for your relationships.
Choice 1 is to use ON DELETE CASCADE. I think that this is not a good practice, though, because an unintended delete can have quite surprising consequences.
Choice 2 is to walk the tree and find the records that need to be deleted. You can use a self-join for your categories table to identify all the children in n levels of the hierarchy. This is hte prefered approach, imo.
Other ideas like triggers are just a variation of 2.