I have two tables
CREATE TABLE `category` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8
CREATE TABLE `item` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
categoryid` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`), KEY `fk_categoryid_item` (`categoryid`),
CONSTRAINT `fk_categoryid_item` FOREIGN KEY (`categoryid`)
REFERENCES `category` (`id`) ON DELETE CASCADE)
ENGINE=InnoDB DEFAULT CHARSET=utf8
In the table category I have a record with id 2.
In the item I have a record with id = 1, categoryid = 2, with 2 as the foreign key referring to the category table. If I delete the row in the category table with the id 2, the record in the item table that has the categoryid as 2 also gets deleted. This is as expected because of on delete cascade. But If I try to drop the table category, I get the error Error Code:
1217. Cannot delete or update a parent row: a foreign key constraint fails
Why does this happen ? Of course, setting foreign_key_checks = 0 dropping the table becomes possible. But I would like to know why does this happen that we can delete the records, but can not drop the table with on cascade delete option. Does this option only apply for deleting records, but not for dropping tables.
I checked the documentation, I could not find any explanation for this.
Please let me know if there is something fundamental that I am missing or if you point out to the related documentation it would be helpful. I am using MySQL 5.7.
Thanks in advance.
If you delete the table category but do not remove/alter the foreign key, then that will be left pointing to nothing. Internally the database has a management system that reinforces the referential constraints and that prevents you from creating lose ends. See also this, this and this questions.
It has something to do also with the math behind it, it is called relational algebra. I am not at that level either, but I think it breaks the definition of a FK if you delete one of the associated tables.
In database relational modeling and implementation, a unique key is a set of zero or more attributes, the value(s) of which are guaranteed to be unique for each tuple (row) in a relation.
I have some sport facilities that have fields that one can play 5x5 football in them. I am trying to make a simple reservation system for them.
My problem is that some fields combine and make bigger fields that the manages of the facilities want to treat them as their own entities (makes sense, if they book them like that why not).
Let's give an actual example.
We have facility FA. They have 3 5x5 fields one next to another, let's call then sa, sb, sc and any two of them can combine to make a 7x7 field, let's call it dd and all three to make a 10x10 field, let's call it te.
This happens with the other facilities as well but this is the more extreme case.
I have been trying to think how to model the tables for the fields when I make the reservation and deal with it but I am not sure.
One solution I have is to have a table for the fields
CREATE TABLE IF NOT EXISTS field (
id SMALLINT(5) UNSIGNED NOT NULL AUTO_INCREMENT,
arena_id SMALLINT(4) UNSIGNED NOT NULL,
internal_id TINYINT(3) UNSIGNED NOT NULL,
is_composite BOOLEAN NOT NULL DEFAULT FALSE,
PRIMARY KEY (id),
UNIQUE (arena_id, internal_id),
CONSTRAINT fk_field_arena_id FOREIGN KEY (arena_id) REFERENCES arena(id) ON UPDATE CASCADE ON DELETE CASCADE
)
;
And theh have a one to one or zero relationship with another table
CREATE TABLE IF NOT EXISTS field_component (
field_id SMALLINT(5) UNSIGNED NOT NULL,
component SMALLINT(5) UNSIGNED NOT NULL,
PRIMARY KEY (field_id, component),
CONSTRAINT fk_field_component_field_id FOREIGN KEY (field_id) REFERENCES field(id) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT fk_field_component_field_id2 FOREIGN KEY (component) REFERENCES field(id) ON UPDATE CASCADE ON DELETE CASCADE
)
;
that will have entries with the fields that comprise a component field. An entry will exist here only when the flag is_composite in the field table is true.
A simpler solution I was thinking that is a bit more manual, was instead of having the second table and the flag, to just have a string column where I put the ids of the fields that make the composite field as a comma separated list.
On a separate note, I was thinking of moving the flag is composite to a third table called field_info that I might have one to one relationship with the field and will contain information about each field. i.e. size, material of the ground, if it's composite or not, notes about it etc.
Any thought suggestions, criticism, alternatives are welcome.
I would consider the following, that ensures in the composite table field_component that the child and composite arenas are at least the same. Note that InnoDB check constraints are not enforced.
Point #1: The is_composite quality in the following for the field_component implicitly pointing back to something that is truly a composite is not enforced. It could be with more compositing (meaning more tables).
Point #2: The datatypes should not be overly engineered into small and tiny INTs at this stage or perhaps ever. Especially if new to mysql.
Point #3: The FK relationships have the tendency to create KEYS for you automatically when not present in the child table. The unique key that we explicitly have in field_component effectly serves two purposes. It enforces non-dupes, and it serves as the index used where an FK auto-gen one would have been generated. Another one is generated automatically as can be seen in show create table. So, our UNIQUE KEY serves a few purposes there.
CREATE TABLE IF NOT EXISTS field (
id SMALLINT(5) UNSIGNED NOT NULL AUTO_INCREMENT,
arena_id SMALLINT(4) UNSIGNED NOT NULL,
internal_id TINYINT(3) UNSIGNED NOT NULL,
is_composite BOOLEAN NOT NULL DEFAULT FALSE,
PRIMARY KEY (id),
UNIQUE (arena_id, internal_id),
CONSTRAINT fk_field_arena_id FOREIGN KEY (arena_id) REFERENCES arena(id) ON UPDATE CASCADE ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS field_component (
field_id SMALLINT(5) UNSIGNED NOT NULL,
component SMALLINT(5) UNSIGNED NOT NULL,
PRIMARY KEY (field_id, component),
CONSTRAINT fk_field_component_field_id FOREIGN KEY (field_id) REFERENCES field(id) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT fk_field_component_field_id2 FOREIGN KEY (component) REFERENCES field(id) ON UPDATE CASCADE ON DELETE CASCADE
);
TweakA:
CREATE SCHEMA TweakA;
USE TweakA;
-- drop table arena
CREATE TABLE IF NOT EXISTS arena
( id INT PRIMARY KEY,
aName varchar(200) NOT NULL
);
-- drop table field
CREATE TABLE IF NOT EXISTS field
( id INT AUTO_INCREMENT PRIMARY KEY,
arena_id INT NOT NULL, -- like the Arena #
internal_id INT NOT NULL, -- 1, 2, 3 for the field #
is_composite BOOLEAN NOT NULL DEFAULT FALSE,
friendly_name VARCHAR(100) NOT NULL,
UNIQUE KEY (arena_id, internal_id),
CONSTRAINT fk_field_arena_id FOREIGN KEY (arena_id) REFERENCES arena(id) ON UPDATE CASCADE ON DELETE CASCADE
);
-- drop table field_component
CREATE TABLE IF NOT EXISTS field_component
( id INT AUTO_INCREMENT PRIMARY KEY,
arena_id INT NOT NULL,
child_internal_id INT NOT NULL,
composite_internal_id INT NOT NULL,
-- The following UK will pick up part of what I will explain in the Narrative
UNIQUE KEY `unq_arena_comp_child` (arena_id,child_internal_id,composite_internal_id),
CONSTRAINT fk_field_child_field_id FOREIGN KEY (arena_id,child_internal_id)
REFERENCES field(arena_id, internal_id) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT fk_field_composite_field_id FOREIGN KEY (arena_id,composite_internal_id)
REFERENCES field(arena_id, internal_id) ON UPDATE CASCADE ON DELETE CASCADE
-- note that InnoDB check constraints are not effective
);
-- Note, look at output from the following
-- show create table field_component; -- this shows the auto-gen of 1 key due to FK
--
-- The following block is a Helper block during testing
-- Truncate in reverse order:
-- TRUNCATE TABLE field_component;
-- TRUNCATE TABLE field;
-- TRUNCATE TABLE arena;
-- test data load:
INSERT arena(id,aName) VALUES (1,'Boston Arena, North Shore');
INSERT field(arena_id,internal_id,is_composite,friendly_name) VALUES
(1,1,FALSE,'sa'),
(1,2,FALSE,'sb'),
(1,3,FALSE,'sc'),
(1,4,TRUE,'dab'),
(1,5,TRUE,'dac'),
(1,6,TRUE,'dbc'),
(1,7,TRUE,'abc');
INSERT field_component(arena_id,child_internal_id,composite_internal_id) VALUES
(1,1,4),
(1,2,4),
(1,1,5),
(1,3,5),
(1,2,6),
(1,3,6),
(1,1,7),
(1,2,7),
(1,3,7); -- SUCCESS
INSERT field_component(arena_id,child_internal_id,composite_internal_id) VALUES
(2,2,4); -- will fail, as expected
INSERT field_component(arena_id,child_internal_id,composite_internal_id) VALUES
(1,72,4); -- will fail, as expected
INSERT field_component(arena_id,child_internal_id,composite_internal_id) VALUES
(1,1,444); -- will fail, as expected
show create table field_component;
-- the above will exhibit the AUTO_INCREMENT gap anomoly due to the above
-- expected failed inserts, setting AI=13 or so
DROP SCHEMA TweakA;
I wrote an FK Enforces Composite Relationship answer that got a little complicated. Yours can go that route depending on the level of DB Enforcement you are looking for.
Also see the MySQL Using FOREIGN KEY Constraints concerning auto-gen of KEYS due to FK relationships as mentioned in Point #3.
So, this answer could just keep growing as you work thru enforcement. Or do it client side. If it were me, I would do it DB Enforcement.
Regardless, as mentioned in comments, don't store CSV values in a column.
I have these tables:
table1
-----------------------
tb1_id
name
other stuff
table2
-------------------------------
tb2_Id
other stuff
table 3
--------------------------------
id
ref Id ->either tb2_id or tb1_id
Can this be achieved from the below code ?
CREATE TABLE `eloan`.`table3` (
`id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`refId` VARCHAR(45) NOT NULL DEFAULT '',
PRIMARY KEY(`id`),
CONSTRAINT `refId` FOREIGN KEY `refId` (`refId`, `refId`)
REFERENCES `table2` (`tb2_id`, `tb1_id`)
ON DELETE RESTRICT
ON UPDATE RESTRICT
)
ENGINE = InnoDB;
This code returned a "duplicate redid" error.
No. That's not possible.
If you want to use just a single refId column, as you show, you will not be able to declare/define foreign key constraint(s) to reference more than one table.
You may be able to define BEFORE INSERT, BEFORE UPDATE and BEFORE DELETE triggers on the three tables, to perform some checks of integrity, and have the trigger throw an exception/error to prevent some changes.
Obviously, you could define two separate columns in table3, one can be a foreign key reference to table1 the other can reference table2. You can define foreign key constraints.
You can allow both of the columns to be NULL.
If you want to enforce only one or the other column to be populated (at least one of the columns has to be NULL and the other column has to be NOT NULL), you can enforce that in BEFORE INSERT and BEFORE UPDATE triggers.
I have the following table:
Create Table if not exists Categories(
category_id int (10) primary key NOT NULL AUTO_INCREMENT,
category_name varchar (20) NOT NULL,
parent_category_id int (10) NOT NULL,
FOREIGN KEY (parent_category_id) REFERENCES Categories(category_id) ON DELETE CASCADE)
The table is holding every category I have on my site - and each category have a parent category (for example 'computer' is the parent category of 'programming')
I have a few top categories which don't have any parent category => parent_category_id =0
My question is how to insert the data for the top categories.
when i'm trying to do:
INSERT INTO `databaseproject`.`categories` (`category_id` ,`category_name` ,`parent_category_id`)
VALUES (NULL , 'computers', '0')
I'm getting the error:
#1452 - Cannot add or update a child row: a foreign key constraint fails (`databaseproject`.`categories`, CONSTRAINT `categories_ibfk_1`
FOREIGN KEY (`parent_category_id`) REFERENCES `categories` (`category_id`) ON DELETE CASCADE)
what can I do to insert those categories?
Make parent_category_id nullable, and parent categories have a null parent_category_id, or add a root row with id 0.
You have two problems. First, category_id is an auto_increment field, meaning the database will create a value for you when you insert a new row, so you don't need to provide it. You certainly can't set it to null, since you have specifically said it can't be null, which is absolutely what you want for an auto-incrementing id field. Just change your insert to:
INSERT INTO 'databaseproject'.'categories' ('category_name' ,'parent_category_id')
VALUES ('computers', '0')
But you still have another problem. parent_category_id has to refer to a valid record in the categories table because of the constraint you created. You can solve this problem by allowing the field to be null (get rid of the "NOT NULL" when creating the parent_category_id), and using null instead of zero to indicate this is a top level record.
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.