MySQL ON DELETE CASCADE not work - mysql

i have two table (type innoDb) why when i deleting main table row like
+note(im using arch os so my database server type is maria db)
DELETE FROM buildings
WHERE
building_no = 2;
relation table rows dont delete ???
CREATE TABLE buildings (
building_no INT PRIMARY KEY AUTO_INCREMENT,
building_name VARCHAR(255) NOT NULL,
address VARCHAR(255) NOT NULL
);
CREATE TABLE rooms (
room_no INT PRIMARY KEY AUTO_INCREMENT,
room_name VARCHAR(255) NOT NULL,
building_no INT NOT NULL,
FOREIGN KEY (building_no)
REFERENCES buildings (building_no)
ON DELETE CASCADE
);

This syntax works for me on MySQL database but i can't see issues in your query too
CREATE TABLE `rooms` (
room_no INT PRIMARY KEY AUTO_INCREMENT,
room_name VARCHAR(255) NOT NULL,
building_no INT NOT NULL,
CONSTRAINT `FK_rooms_1` FOREIGN KEY (`building_no`) REFERENCES `buildings`
(`building_no`) ON DELETE CASCADE
) ENGINE=InnoDB;
or add the constraint after table creation
ALTER TABLE `rooms`
ADD CONSTRAINT `FK_rooms_1` FOREIGN KEY (`building_no`) REFERENCES `buildings` (`building_no`) ON DELETE CASCADE ON UPDATE CASCADE;

Related

How to link one to many relationship with multiple keys pointing on the same table id?

I have a table files and a table users and staff and client.
The file table contain a row made_by a row published_byand a row about_client pointing to a staff, a staff and a client respectively.
One user must be either a staff or a client.
One file can have multiple author (made_by row), but only one user can publish it (published_by), and it can only be about one client (about_client).
First, I put 3 foreign key on files:
CONSTRAINT `made_by_fk` FOREIGN KEY (`made_by`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `published_by_fk` FOREIGN KEY (`published_by`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `about_client_fk` FOREIGN KEY (`about_client`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
but after a little research, I found out that I should put the foreign key on staff / client, and here come the problem, the fk are OPTIONAL. A staff is not obligatory an author of a file, or the client maybe don't have any file attached to it.
I am a bit lost.
DROP TABLE IF EXISTS `files`;
CREATE TABLE IF NOT EXISTS `files` (
`id` INT NOT NULL AUTO_INCREMENT
PRIMARY KEY,
`made_by` INT NOT NULL,
`published_by` INT NOT NULL,
`about_client` INT NOT NULL,
`creation_date` DATETIME NOT NULL,
`modification_date` DATETIME NULL
ON UPDATE CURRENT_TIMESTAMP,
`path` VARCHAR(255) NOT NULL,
`title` VARCHAR(100) NOT NULL UNIQUE,
`category` INT NOT NULL,
`type` VARCHAR(30) NOT NULL,
`size` INT NOT NULL,
CONSTRAINT `made_by_fk` FOREIGN KEY (`made_by`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `published_by_fk` FOREIGN KEY (`published_by`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `about_client_fk` FOREIGN KEY (`about_client`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
)
ENGINE = InnoDB
COLLATE = utf8_unicode_ci;
DROP TABLE IF EXISTS `staff`;
CREATE TABLE IF NOT EXISTS `staff` (
`id` INT NOT NULL AUTO_INCREMENT
PRIMARY KEY,
`job` INT NOT NULL,
`password` VARCHAR(255) NOT NULL
)
ENGINE = InnoDB
COLLATE = utf8_unicode_ci;
DROP TABLE IF EXISTS `users`;
CREATE TABLE IF NOT EXISTS `users` (
`id` INT NOT NULL AUTO_INCREMENT
PRIMARY KEY,
`name` VARCHAR(100) NOT NULL,
`surname` VARCHAR(100) NOT NULL,
`email` VARCHAR(50) NOT NULL UNIQUE
)
ENGINE = InnoDB
COLLATE = utf8_unicode_ci;
DROP TABLE IF EXISTS `clients`;
CREATE TABLE IF NOT EXISTS `clients` (
`id` INT NOT NULL AUTO_INCREMENT
PRIMARY KEY,
`phone` VARCHAR(30) NOT NULL,
`age` INT NOT NULL,
`date_of_birth` DATE NOT NULL,
`security_number` VARCHAR(99) NOT NULL UNIQUE
)
ENGINE = InnoDB
COLLATE = utf8_unicode_ci;
If there can be multiple made_by, it can't be a column in the file table, since that can only contain one value.
You need another table, file_made_by that represents the many-to-many relationship between files and authors.
CREATE TABLE file_made_by (
file_id INT NOT NULL,
author_id INT NOT NULL,
PRIMARY KEY (file_id, author_id),
FOREIGN KEY (file_id) REFERENCES files (id) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (author_id) REFERENCES users (id) ON DELETE CASCADE ON UPDATE CASCADE
);
The clients and staff tables should also include a user_id column that's a foreign key to users.id.
If about_client has to be about a client, not staff, then it should be a foreign key to clients.id rather than users.id.
And if only staff are allowed to be authors, file_made_by.author_id should be a FK to staff.id rather than users.id. The same with files.published_by.

1072 - Key column 'trax_zone_id' doesn't exist in table

this is the parent table
CREATE TABLE trax_zone(
trax_zone_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
trax_zone_name VARCHAR(255) NOT NULL,
)ENGINE=InnoDB;
this is the child table code
CREATE TABLE city(
city_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
city_name VARCHAR(255) NOT NULL,
FOREIGN KEY fk_trax(trax_zone_id) REFERENCES trax_zone(trax_zone_id) ON UPDATE CASCADE ON DELETE RESTRICT,
FOREIGN KEY fk_zoop(zoop_zone_id) REFERENCES zoop_zone(zoop_zone_id) ON UPDATE CASCADE ON DELETE RESTRICT
)ENGINE=InnoDB;
i am new to mysql , kindly guide me

Trouble trying to make these tables

Hey guys I'm running into an issue while trying to create these 5 tables. From what I can tell the issue has to deal with the champ. Every time I try to import my sql file I get an errno 150 stating that the champion table cannot be created.
To clarify a champion can only have one faction but a faction can be composed of many champions. The same relationship for roles and affinity. Thank you for any help in advance.
DROP TABLE IF EXISTS `champion`;
DROP TABLE IF EXISTS `role`;
DROP TABLE IF EXISTS `build`;
DROP TABLE IF EXISTS `faction`;
DROP TABLE IF EXISTS `build_type`;
DROP TABLE IF EXISTS `affinity`;
-- roles table
-- Table consisting of the roles various champions play
CREATE TABLE `role` (
`role_id` int(11) NOT NULL AUTO_INCREMENT,
`role_name` varchar(255) NOT NULL,
PRIMARY KEY (`role_id`)
)ENGINE=InnoDB;
-- build table
CREATE TABLE `build` (
`build_id` int(11) NOT NULL AUTO_INCREMENT,
`build_name` varchar(255) NOT NULL,
PRIMARY KEY (`build_id`),
UNIQUE KEY (`build_name`)
)ENGINE=InnoDB;
-- faction table
-- Table consisting of the faction each champion belongs to
CREATE TABLE `faction`(
`faction_id` int(11) NOT NULL AUTO_INCREMENT,
`faction_name` varchar(255) NOT NULL,
PRIMARY KEY (`faction_id`)
)ENGINE=InnoDB;
-- Champions table
-- Table consisting of various champions in League of Legends
CREATE TABLE `champion`(
`champion_id` int(11) NOT NULL AUTO_INCREMENT,
`champion_name` varchar(255) NOT NULL,
`f_id` int(11) NOT NULL,
`r_id` int(11) NOT NULL,
`a_id` int(11) NOT NULL,
PRIMARY KEY (`champion_id`),
FOREIGN KEY (`r_id`) REFERENCES `role` (`role_id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (`f_id`) REFERENCES `faction` (`faction_id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (`a_id`) REFERENCES `affinity` (`affinity_id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
UNIQUE KEY (`champion_name`)
)ENGINE=InnoDB;
-- build_type table
CREATE TABLE `build_type`(
`cid` int(11) NOT NULL,
`bid` int(11) NOT NULL,
PRIMARY KEY (`cid`, `bid`),
FOREIGN KEY (`cid`) REFERENCES `champion` (`champion_id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (`bid`) REFERENCES `build` (`build_id`)
ON DELETE CASCADE
ON UPDATE CASCADE
)ENGINE=InnoDB;
-- affinity table
-- Table consisting of the affinity a certain champion synergizes
-- with
CREATE TABLE `affinity`(
`affinity_id` int(11) NOT NULL AUTO_INCREMENT,
`affinity_name` varchar(255) NOT NULL,
PRIMARY KEY (`affinity_id`)
)ENGINE=InnoDB;
That's because champion table has a column a_id referring to a table affinity that does not exist yet.To solve this problem you must first create the affinity table before champion table
This
CREATE TABLE `affinity`(
`affinity_id` int(11) NOT NULL AUTO_INCREMENT,
`affinity_name` varchar(255) NOT NULL,
PRIMARY KEY (`affinity_id`)
)ENGINE=InnoDB;
must come before
CREATE TABLE `champion`(
`champion_id` int(11) NOT NULL AUTO_INCREMENT,
`champion_name` varchar(255) NOT NULL,
`f_id` int(11) NOT NULL,
`r_id` int(11) NOT NULL,
`a_id` int(11) NOT NULL,
PRIMARY KEY (`champion_id`),
FOREIGN KEY (`r_id`) REFERENCES `role` (`role_id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (`f_id`) REFERENCES `faction` (`faction_id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (`a_id`) REFERENCES `affinity` (`affinity_id`)
ON DELETE CASCADE
ON UPDATE CASCADE,
UNIQUE KEY (`champion_name`)
)ENGINE=InnoDB;

Mysql create table with multiple foreign key on delete set null

I am trying to create a database with multiple foreign keys with delete/ update constraints, but I got a error code 1005 with following sql scripts:
CREATE TABLE Worker (
WorkerID smallint auto_increment,
WorkerType varchar(45) NOT NULL,
WorkerName varchar(45) NOT NULL,
Position varchar(45) NOT NULL,
TaxFileNumber int NOT NULL,
Address varchar(100) ,
Phone varchar(20) ,
SupervisorID smallint ,
PRIMARY KEY (WorkerID),
FOREIGN KEY (SupervisorID) REFERENCES Worker(WorkerID)
ON DELETE SET NULL
ON UPDATE CASCADE
)Engine=InnoDB;
CREATE TABLE Grape (
GrapeID smallint NOT NULL,
GrapeType varchar(45) NOT NULL,
JuiceConversionRatio int,
StorageContainer ENUM('Stainless Steel Tank','Oak Barrel'),
AgingRequirement int,
PRIMARY KEY (GrapeID)
)Engine=InnoDB;
CREATE TABLE Vineyard (
VineyardID smallint auto_increment,
VineyardName VARCHAR(45) NOT NULL,
FarmerID smallint NOT NULL,
GrapeID smallint NOT NULL,
ComeFrom varchar(45) NOT NULL,
HarvestedAmount int,
RipenessPercent int,
PRIMARY KEY (VineyardID),
FOREIGN KEY (FarmerID) REFERENCES Worker(WorkerID)
ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (GrapeID) REFERENCES Grape(GrapeID)
ON DELETE SET NULL
ON UPDATE CASCADE
)Engine=InnoDB;
The error code says that fail to create the Vineyard table, I just want to know the proper format for creating multiple foreign keys with delete/update control.
Your foreign key rule is ON DELETE SET NULL but your column definition is NOT NULL.
Either change your column definition and remove the NOT NULL part or overthink your foreign key rule. That works:
CREATE TABLE Vineyard (
VineyardID smallint auto_increment,
VineyardName VARCHAR(45) NOT NULL,
FarmerID smallint,
GrapeID smallint,
ComeFrom varchar(45) NOT NULL,
HarvestedAmount int,
RipenessPercent int,
PRIMARY KEY (VineyardID),
FOREIGN KEY (FarmerID) REFERENCES Worker(WorkerID)
ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (GrapeID) REFERENCES Grape(GrapeID)
ON DELETE SET NULL
ON UPDATE CASCADE
)Engine=InnoDB;
SQLFiddle demo
Try with create table(innoDB enginer) without foreign key and use the update table with constraint syntax, for example:
ALTER TABLE `vineyard`
ADD CONSTRAINT `relation_farmer_has_many_vineyards`
FOREIGN KEY (`farmer_id`)
REFERENCES `worker` (`worker_id`)
ON DELETE SET NULL
ON UPDATE CASCADE;
Reference:
http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
Trick: is not recommended to use capital letters(or camel case) in the names of the tables that the behavior differs from the operating system being used:
http://dev.mysql.com/doc/refman/5.1/en/identifier-case-sensitivity.html
Visit :
https://developer.android.com/training/basics/data-storage/databases.html#DefineContract
Cursor c = db.query(
FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
Visit :
http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
CREATE TABLE `ffxi_characterJob` (
`serverID` int(11) NOT NULL,
`userid` int(10)unsigned NOT NULL,
`characterName` varchar(255) NOT NULL,
`jobAbbr` char(4) NOT NULL,
`jobLevel` int(11) default '0',
PRIMARY KEY (`serverID`,`userid`,`characterName`,`jobAbbr`),
INDEX (`jobAbbr`),
CONSTRAINT FOREIGN KEY (`serverID`,`userid`,`characterName`) REFERENCES `ffxi_characters` (`serverID`,`userid`,`characterName`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY (`jobAbbr`) REFERENCES `ffxi_jobType` (`jobAbbr`) ON DELETE CASCADE ON UPDATE CASCADE
) TYPE=InnoDB;

How do I use on delete cascade in mysql?

I have a database of components. Each component is of a specific type. That means there is a many-to-one relationship between a component and a type. When I delete a type, I would like to delete all the components which has a foreign key of that type. But if I'm not mistaken, cascade delete will delete the type when the component is deleted. Is there any way to do what I described?
Here's what you'd include in your components table.
CREATE TABLE `components` (
`id` int(10) unsigned NOT NULL auto_increment,
`typeId` int(10) unsigned NOT NULL,
`moreInfo` VARCHAR(32),
-- etc
PRIMARY KEY (`id`),
KEY `type` (`typeId`)
CONSTRAINT `myForeignKey` FOREIGN KEY (`typeId`)
REFERENCES `types` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
)
Just remember that you need to use the InnoDB storage engine: the default MyISAM storage engine doesn't support foreign keys.
use this sql
DELETE T1, T2
FROM T1
INNER JOIN T2 ON T1.key = T2.key
WHERE condition
You have to define your Foreign Key constraints as ON DELETE CASCADE.
Note: You need to use InnoDB storage engine, the default MyISAM storage engine not support foreign keys relation.
CREATE TABLE `table2` (
`id` int(11) NOT NULL auto_increment,
`name` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `ids` (`ids`)
CONSTRAINT `foreign` FOREIGN KEY (`ids`)
REFERENCES `table2` (`ids`) ON DELETE CASCADE ON UPDATE CASCADE
)
Step 1. Create the buildings table:
CREATE TABLE buildings (
building_no INT PRIMARY KEY AUTO_INCREMENT,
building_name VARCHAR(255) NOT NULL,
address VARCHAR(255) NOT NULL
);
Step 2. Create the rooms table:
CREATE TABLE rooms (
room_no INT PRIMARY KEY AUTO_INCREMENT,
room_name VARCHAR(255) NOT NULL,
building_no INT NOT NULL,
FOREIGN KEY (building_no)
REFERENCES buildings (building_no)
ON DELETE CASCADE
);
Notice that the ON DELETE CASCADE clause at the end of the foreign key constraint
definition.