Writing trigger in MySQL regarding two tables, with logic - mysql

When I write trigger mentioned below I get error "INSERT not expected here"
Tables movies, Lightning is many to many relation with associative table.
My aim is to get Lumens_power in 'Lightning' table set as 5300 when Movies table 'genre' attribute is equal to 'action' .
CREATE DEFINER = CURRENT_USER TRIGGER `Film_industry`.`Movies_AFTER_INSERT`
AFTER INSERT ON `Movies` FOR EACH ROW
BEGIN
SELECT genre,
CASE WHEN genre = 'action' THEN INSERT INTO Lightning(id, type, Lumens_power) values('NEW.Movies_id', 'directed', '5300');
END;
FROM Movies;
END;
-- -----------------------------------------------------
-- Table `Film_industry`.`Movies`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Film_industry`.`Movies` (
`id` INT NOT NULL AUTO_INCREMENT,
`title` VARCHAR(100) NOT NULL,
`released_on` DATE NOT NULL,
`genre` VARCHAR(40) NOT NULL,
`rating` DECIMAL(2,1) NOT NULL,
`finansial_stake` DECIMAL(11,2) NOT NULL,
`Supporting_object_id` INT NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `id_UNIQUE` (`id` ASC) VISIBLE,
UNIQUE INDEX `title_UNIQUE` (`title` ASC) VISIBLE,
INDEX `fk_Movies_Supporting_object1_idx` (`Supporting_object_id` ASC) VISIBLE,
CONSTRAINT `fk_Movies_Supporting_object1`
FOREIGN KEY (`Supporting_object_id`)
REFERENCES `Film_industry`.`Supporting_object` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Film_industry`.`Lightning`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Film_industry`.`Lightning` (
`id` INT NOT NULL AUTO_INCREMENT,
`type` VARCHAR(45) NOT NULL,
`Lumens_power` INT NOT NULL,
`Scene_id` INT NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_Lightning_Scene1_idx` (`Scene_id` ASC) VISIBLE,
CONSTRAINT `fk_Lightning_Scene1`
FOREIGN KEY (`Scene_id`)
REFERENCES `Film_industry`.`Scene` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;

You can check the value for the genre column simply using
IF (NEW.genre = 'action') then
INSERT...
END;
Note that the Lightning-table also contains Scene_id which references the Film_industry.Scene.id. It is defined as NOT NULL, so you need to come up with the logic to set it appropriately.

Related

Error 1136: Column count doesn't match value count at row 1. Can't find unmatching columns

I keep getting this error when I try to build this little database:
ERROR: Error 1136: Column count doesn't match value count at row 1
SQL Code:
INSERT INTO area (name, description)
VALUES ('National'),
('The place for all National political issues.')
SQL script execution finished: statements: 19 succeeded, 1 failed
It seems like all of my column counts match so I have no idea where I'm going wrong. I think the problem is happening with my inserts. I'm using MySQLWorkbench and the problem happens each time I try to build the database from scratch. Any help would be appreciated!
Thank you.
-- MySQL Workbench Forward Engineering
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
-- -----------------------------------------------------
-- Schema RvB
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema RvB
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `RvB` DEFAULT CHARACTER SET utf8 ;
USE `RvB` ;
-- -----------------------------------------------------
-- Table `RvB`.`area`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `RvB`.`area` (
`name` VARCHAR(100) NOT NULL,
`description` VARCHAR(200) NULL,
PRIMARY KEY (`name`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `RvB`.`links`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `RvB`.`links` (
`id` INT NOT NULL AUTO_INCREMENT,
`link` VARCHAR(999) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `RvB`.`affiliation`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `RvB`.`affiliation` (
`id` INT NOT NULL AUTO_INCREMENT,
`affiliation` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `RvB`.`privilege`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `RvB`.`privilege` (
`id` INT NOT NULL AUTO_INCREMENT,
`privilege` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `RvB`.`pages`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `RvB`.`pages` (
`id` INT NOT NULL AUTO_INCREMENT,
`title` VARCHAR(200) NOT NULL,
`area` VARCHAR(100) NOT NULL,
PRIMARY KEY (`id`),
INDEX `area_idx` (`area` ASC) VISIBLE,
CONSTRAINT `area`
FOREIGN KEY (`area`)
REFERENCES `RvB`.`area` (`name`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `RvB`.`accounts`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `RvB`.`accounts` (
`username` VARCHAR(20) NOT NULL,
`email` VARCHAR(100) NOT NULL,
`party` INT NOT NULL,
`password` VARCHAR(40) NOT NULL,
`creation_date` DATE NULL,
`privileges` INT NOT NULL,
PRIMARY KEY (`username`),
INDEX `party_idx` (`party` ASC) VISIBLE,
INDEX `privileges_idx` (`privileges` ASC) VISIBLE,
CONSTRAINT `party`
FOREIGN KEY (`party`)
REFERENCES `RvB`.`affiliation` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `privileges`
FOREIGN KEY (`privileges`)
REFERENCES `RvB`.`privilege` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `RvB`.`posts`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `RvB`.`posts` (
`id` INT NOT NULL AUTO_INCREMENT,
`username` VARCHAR(20) NOT NULL,
`affiliation` INT NOT NULL,
`post_text` VARCHAR(9999) NULL,
`time_and_date` DATETIME(4) NOT NULL,
`votes` INT NOT NULL DEFAULT 0,
`page` INT NOT NULL,
`post_title` VARCHAR(500) NOT NULL,
PRIMARY KEY (`id`),
INDEX `page_idx` (`page` ASC) VISIBLE,
INDEX `affiliation_idx` (`affiliation` ASC) VISIBLE,
INDEX `username_idx` (`username` ASC) VISIBLE,
CONSTRAINT `page`
FOREIGN KEY (`page`)
REFERENCES `RvB`.`pages` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `affiliation`
FOREIGN KEY (`affiliation`)
REFERENCES `RvB`.`affiliation` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `username`
FOREIGN KEY (`username`)
REFERENCES `RvB`.`accounts` (`username`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `RvB`.`postComments`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `RvB`.`postComments` (
`id` INT NOT NULL AUTO_INCREMENT,
`post_id` INT NOT NULL,
`username` VARCHAR(20) NOT NULL,
`text` VARCHAR(8000) NULL,
`date` DATETIME NULL,
PRIMARY KEY (`id`),
INDEX `post_id_idx` (`post_id` ASC) VISIBLE,
INDEX `username_idx` (`username` ASC) VISIBLE,
CONSTRAINT `postid`
FOREIGN KEY (`post_id`)
REFERENCES `RvB`.`posts` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `user-name`
FOREIGN KEY (`username`)
REFERENCES `RvB`.`accounts` (`username`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `RvB`.`contactUs`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `RvB`.`contactUs` (
`id` INT NOT NULL AUTO_INCREMENT,
`email` VARCHAR(150) NOT NULL,
`message` VARCHAR(2000) NULL,
`name` VARCHAR(150) NULL,
`date` DATETIME NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
-- begin attached script 'script'
INSERT INTO privilege (privilege)
VALUES ('reg_user'),
('moderator'),
('archmoderator'),
('admin');
INSERT INTO affiliation (affiliation)
VALUES ('republican'),
('democrat'),
('libertarian'),
('green'),
('constitution');
INSERT INTO area (name, description)
VALUES ('National'),
('The place for all National political issues.');
INSERT INTO area (name, description)
VALUES ('Colorado'),
('The place for all Colorado issues or politicians.');
INSERT INTO pages (title, area)
VALUES ('Abortion'),
('National');
INSERT INTO accounts (username, email, party, password, creation_date, privileges)
VALUES ('dan_the_repub'),
('republican#gmail.com'),
('1'),
('password'),
('2020-09-14'),
('1');
INSERT INTO accounts (username, email, party, password, creation_date, privileges)
VALUES ('kendra_the_demo'),
('democratsRus#gmail.com'),
('2'),
('password'),
('2020-09-13'),
('1');
INSERT INTO posts (username, affiliation, post_text, time_and_date, votes, page, post_title)
VALUES ('dan_the_repub'),
('1'),
('Republicans rule!!'),
('2020-09-15 12:43:10'),
('20'),
('1'),
('What I think about Republicans, a statement');
INSERT INTO posts (username, affiliation, post_text, time_and_date, votes, page, post_title)
VALUES ('kendra_the_demo'),
('2'),
('Go go go go Democrats!!'),
('2020-09-13 11:42:05'),
('25'),
('1'),
('Democrats are the best! Everyone else stinks!');
-- end attached script 'script'
Each parenthesized group after VALUES is a single row, with an expression for each column in it. If you want to insert 1 row with 2 columns, you should just have a single group.
VALUES ('National', 'The place for all National political issues.')
Your code is trying to insert 2 rows, but it's only supplying a value for 1 column in each row. The number of expressions in each group has to match the number of columns in the list after INSERT INTO area.

Failed to add the foreign key constraint. Missing column 'gym_id' for constraint 'fk_gyms_instructors_gyms' in the referenced table 'gyms'

I'm forward engineering a database from an ERD that I created in MySqlWorkbench. I have a very basic many to many relationship between the "gyms" table and the "instructors" table, but I'm getting the error above. To me, the error reads that MySql can't find the "gym_id" column in the "gyms" table when it tries to create the many-to-many table.
I don't know why that would be the case.
I've went through the tables to make sure there were no typos and that the data types matched. I also went through the execution script to make sure the "gyms" table was being created before the many-to-many. It was. I can't sniff out what is causing the error. So any help or suggestion is appreciated
This is the error:
Executing SQL script in server
ERROR: Error 3734: Failed to add the foreign key constraint. Missing column 'gym_id' for constraint 'fk_gyms_instructors_gyms' in the referenced table 'gyms'
SQL Code:
-- -----------------------------------------------------
-- Table `fitness`.`gyms_instructors`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fitness`.`gyms_instructors` (
`id` INT NOT NULL AUTO_INCREMENT,
`gym_id` SMALLINT NOT NULL,
`instructor_id` SMALLINT NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_gyms_instructors_gyms_idx` (`gym_id` ASC) VISIBLE,
INDEX `fk_gyms_instructors_instructors_idx` (`instructor_id` ASC) VISIBLE,
CONSTRAINT `fk_gyms_instructors_gyms`
FOREIGN KEY (`gym_id`)
REFERENCES `fitness`.`gyms` (`gym_id`)
ON DELETE NO ACTION
ON UPDATE CASCADE,
CONSTRAINT `fk_gyms_instructors_instructors`
FOREIGN KEY (`instructor_id`)
REFERENCES `fitness`.`instructors` (`instructor_id`)
ON DELETE NO ACTION
ON UPDATE CASCADE)
ENGINE = InnoDB
SQL script execution finished: statements: 10 succeeded, 1 failed
Fetching back view definitions in final form.
Nothing to fetch
The other potentially useful information is:
1. On the many to many table, in the foreign keys section both gym_id and instructor_id are SMALLINTS and NOT NULL,
2. On their respective table the gym_id and instructor_id are autoincrementing primary keys, NOT NULL
3. I pasted the full script below if you want to look.
-- MySQL Workbench Forward Engineering
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
-- -----------------------------------------------------
-- Schema fitness
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema fitness
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `fitness` DEFAULT CHARACTER SET utf8 ;
USE `fitness` ;
-- -----------------------------------------------------
-- Table `fitness`.`fitness_classes`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fitness`.`fitness_classes` (
`fitness_class_id` INT NOT NULL AUTO_INCREMENT,
`title` VARCHAR(45) NOT NULL,
`price` DECIMAL(2,2) NOT NULL,
`description` VARCHAR(500) NOT NULL,
`vacancies` INT NOT NULL,
`start_time` DATETIME NOT NULL,
PRIMARY KEY (`fitness_class_id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `fitness`.`categories`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fitness`.`categories` (
`category_id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`description` TEXT(1200) NULL,
PRIMARY KEY (`category_id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `fitness`.`tags`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fitness`.`tags` (
`id` INT NOT NULL AUTO_INCREMENT,
`fitness_class_id` INT NOT NULL,
`category_id` INT NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_tags_fitness_classes_idx` (`fitness_class_id` ASC) VISIBLE,
INDEX `fk_tags_categories_idx` (`category_id` ASC) VISIBLE,
CONSTRAINT `fk_tags_fitness_classes`
FOREIGN KEY (`fitness_class_id`)
REFERENCES `fitness`.`fitness_classes` (`fitness_class_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_tags_categories`
FOREIGN KEY (`category_id`)
REFERENCES `fitness`.`categories` (`category_id`)
ON DELETE NO ACTION
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `fitness`.`gyms`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fitness`.`gyms` (
`gym_id` SMALLINT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(55) NOT NULL,
`address` VARCHAR(55) NOT NULL,
`city` VARCHAR(25) NOT NULL,
`state` VARCHAR(25) NOT NULL,
`phone` VARCHAR(10) NOT NULL,
`latitude` DECIMAL(10,8) NULL,
`longitude` DECIMAL(10,8) NULL,
`neighborhood` VARCHAR(45) NOT NULL,
`create_time` TIMESTAMP NOT NULL,
PRIMARY KEY (`gym_id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `fitness`.`instructors`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fitness`.`instructors` (
`instructor_id` SMALLINT NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(55) NOT NULL,
`last_name` VARCHAR(55) NOT NULL,
`create_time` TIMESTAMP NOT NULL,
PRIMARY KEY (`instructor_id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `fitness`.`gyms_instructors`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fitness`.`gyms_instructors` (
`id` INT NOT NULL AUTO_INCREMENT,
`gym_id` SMALLINT NOT NULL,
`instructor_id` SMALLINT NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_gyms_instructors_gyms_idx` (`gym_id` ASC) VISIBLE,
INDEX `fk_gyms_instructors_instructors_idx` (`instructor_id` ASC) VISIBLE,
CONSTRAINT `fk_gyms_instructors_gyms`
FOREIGN KEY (`gym_id`)
REFERENCES `fitness`.`gyms` (`gym_id`)
ON DELETE NO ACTION
ON UPDATE CASCADE,
CONSTRAINT `fk_gyms_instructors_instructors`
FOREIGN KEY (`instructor_id`)
REFERENCES `fitness`.`instructors` (`instructor_id`)
ON DELETE NO ACTION
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `fitness`.`listings`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fitness`.`listings` (
`id` INT NOT NULL AUTO_INCREMENT,
`gym_id` SMALLINT NOT NULL,
`fitness_class_id` INT NOT NULL,
`instructor_id` SMALLINT NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_listings_gym_idx` (`gym_id` ASC) VISIBLE,
INDEX `fk_listings_fitness_class_idx` (`fitness_class_id` ASC) VISIBLE,
INDEX `fk_listings_instructor_idx` (`instructor_id` ASC) VISIBLE,
CONSTRAINT `fk_listings_gym`
FOREIGN KEY (`gym_id`)
REFERENCES `fitness`.`gyms` (`gym_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_listings_fitness_class`
FOREIGN KEY (`fitness_class_id`)
REFERENCES `fitness`.`fitness_classes` (`fitness_class_id`)
ON DELETE NO ACTION
ON UPDATE CASCADE,
CONSTRAINT `fk_listings_instructor`
FOREIGN KEY (`instructor_id`)
REFERENCES `fitness`.`instructors` (`instructor_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `fitness`.`users`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fitness`.`users` (
`user_id` INT NOT NULL AUTO_INCREMENT,
`email` VARCHAR(255) NOT NULL,
`password` VARCHAR(32) NOT NULL,
`create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`username` VARCHAR(16) NOT NULL,
PRIMARY KEY (`user_id`));
-- -----------------------------------------------------
-- Table `fitness`.`reviews`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fitness`.`reviews` (
`review_id` INT NOT NULL AUTO_INCREMENT,
`fitness_class_id` INT NOT NULL,
`rating` TINYINT(1) NOT NULL,
`review_text` TEXT(1200) NULL,
`create_time` TIMESTAMP NOT NULL,
PRIMARY KEY (`review_id`),
INDEX `fk_reviews_classes_idx` (`fitness_class_id` ASC) VISIBLE,
CONSTRAINT `fk_reviews_classes`
FOREIGN KEY (`fitness_class_id`)
REFERENCES `fitness`.`fitness_classes` (`fitness_class_id`)
ON DELETE NO ACTION
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `fitness`.`bookings`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fitness`.`bookings` (
`booking_id` INT NOT NULL AUTO_INCREMENT,
`fitness_class_id` INT NOT NULL,
`user_id` INT NOT NULL,
`price` DECIMAL(2,2) NOT NULL,
`class_start_time` DATETIME NOT NULL,
`purchase_date` DATETIME NOT NULL,
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`booking_id`),
CONSTRAINT `user_id`
FOREIGN KEY ()
REFERENCES `fitness`.`users` ()
ON DELETE NO ACTION
ON UPDATE CASCADE,
CONSTRAINT `fitness_class_id`
FOREIGN KEY ()
REFERENCES `fitness`.`fitness_classes` ()
ON DELETE NO ACTION
ON UPDATE CASCADE)
ENGINE = InnoDB;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;

SQL Script can't create some tables

My SQL script firstly says that it is not connected, when i open it, so i connect it by going to Query -> Reconnect to server, which works. Then i try to execute the SQL script which only creates the first two tables are met with an error code 1064, and the errors are at the VISIBLE Index lines. I have no idea what that means as i am completely new to SQL, can anyone help?
Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' INDEX userId_idx (userId ASC) VISIBLE, CONSTRAINT gameId FOREIGN ' at line 9
-- MySQL Script generated by MySQL Workbench
-- Wed Jan 2 02:21:44 2019
-- Model: New Model Version: 1.0
-- MySQL Workbench Forward Engineering
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema game_review
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema game_review
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `game_review` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ;
USE `game_review` ;
-- -----------------------------------------------------
-- Table `game_review`.`games`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `game_review`.`games` (
`game_Id` INT NOT NULL AUTO_INCREMENT,
`title` VARCHAR(255) NOT NULL,
`tags` VARCHAR(60) NOT NULL,
`systemReq` VARCHAR(255) NOT NULL,
`developer` VARCHAR(45) NOT NULL,
`publisher` VARCHAR(45) NOT NULL,
`trailer` VARCHAR(45) NULL,
`about` VARCHAR(255) NULL,
`platform` VARCHAR(45) NOT NULL,
`categories` VARCHAR(45) NOT NULL,
`description` VARCHAR(45) NOT NULL,
`releaseDate` DATETIME NOT NULL,
PRIMARY KEY (`game_Id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `game_review`.`users`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `game_review`.`users` (
`user_Id` INT NOT NULL AUTO_INCREMENT,
`username` VARCHAR(45) NOT NULL,
`password` VARCHAR(45) NOT NULL,
`email` VARCHAR(45) NOT NULL,
PRIMARY KEY (`user_Id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `game_review`.`reviews`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `game_review`.`reviews` (
`review_Id` INT NOT NULL AUTO_INCREMENT,
`gameId` INT NOT NULL,
`userId` INT NOT NULL,
`review` TEXT(1024) NOT NULL,
`rating` INT NULL,
`dateposted` DATETIME NULL,
PRIMARY KEY (`review_Id`),
INDEX `gameId_idx` (`gameId` ASC) VISIBLE,
INDEX `userId_idx` (`userId` ASC) VISIBLE,
CONSTRAINT `gameId`
FOREIGN KEY (`gameId`)
REFERENCES `game_review`.`games` (`game_Id`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `userId`
FOREIGN KEY (`userId`)
REFERENCES `game_review`.`users` (`user_Id`)
ON DELETE CASCADE
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `game_review`.`favourites`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `game_review`.`favourites` (
`favourites_Id` INT NOT NULL AUTO_INCREMENT,
`gameId` INT NOT NULL,
`userId` INT NOT NULL,
PRIMARY KEY (`favourites_Id`),
INDEX `gameId_idx` (`gameId` ASC) VISIBLE,
INDEX `userId_idx` (`userId` ASC) VISIBLE,
CONSTRAINT `gameId`
FOREIGN KEY (`gameId`)
REFERENCES `game_review`.`games` (`game_Id`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `userId`
FOREIGN KEY (`userId`)
REFERENCES `game_review`.`users` (`user_Id`)
ON DELETE CASCADE
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `game_review`.`forum`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `game_review`.`forum` (
`forum_Id` INT NOT NULL AUTO_INCREMENT,
`gameId` INT NOT NULL,
`userId` INT NOT NULL,
`topic` VARCHAR(45) NOT NULL,
`views` INT NOT NULL,
`likes` INT NOT NULL,
`comment` TEXT(300) NULL,
`totalComments` INT NULL,
`dateposted` DATETIME NOT NULL,
PRIMARY KEY (`forum_Id`),
INDEX `gameId_idx` (`gameId` ASC) VISIBLE,
INDEX `userId_idx` (`userId` ASC) VISIBLE,
CONSTRAINT `gameId`
FOREIGN KEY (`gameId`)
REFERENCES `game_review`.`games` (`game_Id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `userId`
FOREIGN KEY (`userId`)
REFERENCES `game_review`.`users` (`user_Id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `game_review`.`game cart`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `game_review`.`game cart` (
`cart_Id` INT NOT NULL AUTO_INCREMENT,
`gameId` INT NOT NULL,
`quantity` INT NULL,
PRIMARY KEY (`cart_Id`),
INDEX `gameId_idx` (`gameId` ASC) VISIBLE,
CONSTRAINT `gameId`
FOREIGN KEY (`gameId`)
REFERENCES `game_review`.`games` (`game_Id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
Your declaration of indexes is not correct : VISIBLE is not recognized syntax. Also, the ASC mention is superfluous as it corrresponds to the default.
Replace :
...
INDEX `gameId_idx` (`gameId` ASC) VISIBLE,
INDEX `userId_idx` (`userId` ASC) VISIBLE,
...
With :
...
INDEX `reviews_gameId_idx` (`gameId`),
INDEX `reviews_userId_idx` (`userId`),
...
For more information see the mysql CREATE INDEX docs.
Also please bear in mind that, in most RDBMS others than mysql, index names are global across the database schema, hence make sure not to use the same index name twice (I can see that at least index gameId_idx is declared twice. One solution is to prefix the index name with the table it belongs to, as shown above.
Foreign key names between different tables also must be unique (you have duplicates like game_Id).
Finally I also notice that one of your table name has a space in it (game cart) : this is not a good practice, should be avoided.

Cannot add foreign key constraint, workbench

I used workbench to implement a database schema, but I'm getting this error when using foreign keys in a certain table.
1215 - Cannot add foreign key constraint
SQL query:
CREATE TABLE IF NOT EXISTS `Gam3ty`.`Frequently_Used_Location` (
`idFrequently_Used_Location` INT NOT NULL,
`User_idUser` INT NOT NULL,
`User_College_idCollege` INT NOT NULL,
PRIMARY KEY (`idFrequently_Used_Location`,`User_idUser`,`User_College_idCollege`),
INDEX `fk_Frequently_Used_Location_User1_idx` (`User_idUser` ASC,`User_College_idCollege` ASC),
CONSTRAINT `fk_Frequently_Used_Location_User1`
FOREIGN KEY (`User_idUser` , `User_College_idCollege`)
REFERENCES `Gam3ty`.`User` (`idUser` , `College_idCollege`)
my SQL:
CREATE SCHEMA IF NOT EXISTS `Gam3ty` DEFAULT CHARACTER SET utf8 ;
USE `Gam3ty` ;
-- -----------------------------------------------------
-- Table `Gam3ty`.`Frequently_Used_Location`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Gam3ty`.`Frequently_Used_Location` (
`idFrequently_Used_Location` INT NOT NULL,
`User_idUser` INT NOT NULL,
`User_College_idCollege` INT NOT NULL,
PRIMARY KEY (`idFrequently_Used_Location`, `User_idUser`, `User_College_idCollege`),
INDEX `fk_Frequently_Used_Location_User1_idx` (`User_idUser` ASC, `User_College_idCollege` ASC),
CONSTRAINT `fk_Frequently_Used_Location_User1`
FOREIGN KEY (`User_idUser` , `User_College_idCollege`)
REFERENCES `Gam3ty`.`User` (`idUser` , `College_idCollege`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Gam3ty`.`Location`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Gam3ty`.`Location` (
`idLocation` INT NOT NULL,
`Frequently_Used_Location_idFrequently_Used_Location` INT NOT NULL,
`Frequently_Used_Location_User_idUser` INT NOT NULL,
`Frequently_Used_Location_User_College_idCollege` INT NOT NULL,
`type` VARCHAR(45) NULL,
PRIMARY KEY (`idLocation`),
INDEX `fk_Location_Frequently_Used_Location1_idx` (`Frequently_Used_Location_idFrequently_Used_Location` ASC, `Frequently_Used_Location_User_idUser` ASC, `Frequently_Used_Location_User_College_idCollege` ASC),
CONSTRAINT `fk_Location_Frequently_Used_Location1`
FOREIGN KEY (`Frequently_Used_Location_idFrequently_Used_Location` , `Frequently_Used_Location_User_idUser` , `Frequently_Used_Location_User_College_idCollege`)
REFERENCES `Gam3ty`.`Frequently_Used_Location` (`idFrequently_Used_Location`, `User_idUser` , `User_College_idCollege`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Gam3ty`.`University`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Gam3ty`.`University` (
`idUniversity` INT NOT NULL,
`Location_idLocation` INT NOT NULL,
`Info` VARCHAR(45) NULL,
PRIMARY KEY (`idUniversity`, `Location_idLocation`),
INDEX `fk_University_Location1_idx` (`Location_idLocation` ASC),
CONSTRAINT `fk_University_Location1`
FOREIGN KEY (`Location_idLocation`)
REFERENCES `Gam3ty`.`Location` (`idLocation`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Gam3ty`.`College`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Gam3ty`.`College` (
`idCollege` INT NOT NULL,
`University_idUniversity` INT NOT NULL,
`Location_idLocation` INT NOT NULL,
`Info` VARCHAR(45) NULL,
`Staff` VARCHAR(45) NULL,
`Department` VARCHAR(45) NULL,
PRIMARY KEY (`idCollege`, `University_idUniversity`, `Location_idLocation`),
INDEX `fk_College_University1_idx` (`University_idUniversity` ASC),
INDEX `fk_College_Location1_idx` (`Location_idLocation` ASC),
CONSTRAINT `fk_College_University1`
FOREIGN KEY (`University_idUniversity`)
REFERENCES `Gam3ty`.`University` (`idUniversity`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_College_Location1`
FOREIGN KEY (`Location_idLocation`)
REFERENCES `Gam3ty`.`Location` (`idLocation`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Gam3ty`.`User`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Gam3ty`.`User` (
`idUser` INT NOT NULL,
`College_idCollege` INT NOT NULL,
`UserName` VARCHAR(45) NOT NULL,
`Password` VARCHAR(45) NOT NULL,
`E-mail` VARCHAR(45) NOT NULL,
`Social_media_accounts` VARCHAR(45) NULL,
`Gender` VARCHAR(45) NOT NULL,
`Job` VARCHAR(45) NOT NULL,
`Tel-num` BIGINT(11) NULL,
`Adress` VARCHAR(45) NULL,
PRIMARY KEY (`idUser`, `College_idCollege`, `UserName`),
INDEX `fk_User_College_idx` (`College_idCollege` ASC),
CONSTRAINT `fk_User_College`
FOREIGN KEY (`College_idCollege`)
REFERENCES `Gam3ty`.`College` (`idCollege`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
I checked the datatypes and they are all the same, also every foreign key is a primary key in it's original table.
Tables are created in order from top to bottom when you run a SQL script.
You can't create a foreign key that references a table that hasn't been created yet.
You must order the tables so that each table is created before any tables that reference it.
#Rahul wrote:
You need to refer all of the columns designated as primary key.
I agree this is a recommended practice, because otherwise you can create a foreign key where a given row references multiple rows in the parent table. This leads to ambiguous semantics. For instance, can you delete a row in the parent table if there's a row referencing it in the child table, but there's a second row in the parent table that satisfies the reference? This breaks the definition of referential integrity in standard SQL.
Nevertheless, InnoDB allows it. You can make a foreign key that references any left-most subset of columns of any key (unique or non-unique). It's a very bad idea, but InnoDB lets you do it and does not throw an error.
The following is crazy, but it's not an error to InnoDB:
create table foo (a int, b int, key (a, b));
create table bar (a int, foreign key (a) references foo(a));
That's cause table Gam3ty.User defines primary key on 3 columns as seen below but you are referencing only two of them. which creates partial functional dependency. You need to refer all of the columns designated as primary key
CREATE TABLE IF NOT EXISTS `Gam3ty`.`User` (
....
PRIMARY KEY (`idUser`, `College_idCollege`, `UserName`)
Your referencing table
FOREIGN KEY (`User_idUser` , `User_College_idCollege`)
REFERENCES `Gam3ty`.`User` (`idUser` , `College_idCollege`)

SQL Schema Level Constraint

I've got a constraint between some tables I'm trying to implement, I imagine I should be doing it on the db level, but I'm struggling to come up with the right terms to google, maybe you guys can help!
If I have the tables:
Product [coke, banana, chocolate etc]
ProductType [food, drink, cosmetics etc]
Location [fridge, shelf, cupboard etc]
If -> is many-to-one, and >-< is many-to-many
Product -> ProductType
Product -> Location
ProductType >-< Location
Given a fridge, we know a fridge can contain [food,drink], so on the application level, we present the user with only the food and drink products to allocate to fridge. Is there a way on the db level to ensure that fridge only contains products from its permitted types?
Below is the SQL code I came up with for the above, in the last part I insert 'coke', with ProductType 'drink'. How to I make sure it therefore can't be put in a 'cupboard'
CREATE SCHEMA IF NOT EXISTS `test` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `test` ;
-- -----------------------------------------------------
-- Table `test`.`Location`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test`.`Location` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `test`.`ProductType`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test`.`ProductType` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `test`.`Product`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test`.`Product` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NULL,
`Location_id` INT NULL,
`ProductType_id` INT NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_Product_Location_idx` (`Location_id` ASC),
INDEX `fk_Product_ProductType1_idx` (`ProductType_id` ASC),
CONSTRAINT `fk_Product_Location`
FOREIGN KEY (`Location_id`)
REFERENCES `test`.`Location` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Product_ProductType1`
FOREIGN KEY (`ProductType_id`)
REFERENCES `test`.`ProductType` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `test`.`ProductType_has_Location`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `test`.`ProductType_has_Location` (
`ProductType_id` INT NOT NULL,
`Location_id` INT NOT NULL,
PRIMARY KEY (`ProductType_id`, `Location_id`),
INDEX `fk_ProductType_has_Location_Location1_idx` (`Location_id` ASC),
INDEX `fk_ProductType_has_Location_ProductType1_idx` (`ProductType_id` ASC),
CONSTRAINT `fk_ProductType_has_Location_ProductType1`
FOREIGN KEY (`ProductType_id`)
REFERENCES `test`.`ProductType` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_ProductType_has_Location_Location1`
FOREIGN KEY (`Location_id`)
REFERENCES `test`.`Location` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
INSERT INTO `test`.`Location`
(`name`)
VALUES
('fridge'),('shelf'),('cupboard');
INSERT INTO `test`.`ProductType`
(`name`)
VALUES
('food'),('drink'),('cosmetics');
INSERT INTO `test`.`ProductType_has_Location`
(`ProductType_id`,`Location_id`)
VALUES
(1,1),(2,1),(2,2),(3,3);
INSERT INTO `test`.`Product`
(`name`,`ProductType_id`,`Location_id`)
VALUES
('coke',2,NULL);
Another constraint in Product:
CONSTRAINT `fk_Product_Location_XRef`
FOREIGN KEY (`ProductType_id`,`Location_id`)
REFERENCES `test`.`ProductType_has_Location` (`ProductType_id`,`Location_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
This then checks that the Type and Location agree with what's in the ProductType_has_Location table.