MySQL triger to set foreign key to null - mysql

I have table named Webpage_Categories (MySQL)
Webpage_Categories
-----------------
webpage_catgegory_id | parent_id | name
where parent_id field is foreign key, which references the webpage_category_id field.
Here is the create table statement:
CREATE TABLE `webpage_category` (
`webpage_category_id` int(11) NOT NULL AUTO_INCREMENT,
`parent_id` int(11) DEFAULT NULL,
`name` varchar(255) NOT NULL,
`name_en` varchar(255) DEFAULT NULL,
`thumbnail_image` varchar(255) DEFAULT NULL,
`thumbnail_image_en` varchar(255) DEFAULT NULL,
`display_date` tinyint(4) NOT NULL,
`display_thumbnail_image` tinyint(4) NOT NULL,
`display_short_text` tinyint(4) NOT NULL,
`display_more_button` tinyint(4) NOT NULL,
`imported_from_old_site` tinyint(4) NOT NULL,
`slug` varchar(255) NOT NULL,
`slug_en` varchar(255) DEFAULT NULL,
`sort_order` int(11) NOT NULL,
`visible` tinyint(4) NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime DEFAULT NULL,
`deleted_at` datetime DEFAULT NULL,
`deleted_by` int(11) DEFAULT NULL,
`deleted_from_ip` varchar(255) DEFAULT NULL,
`deleted_with_browser` varchar(255) DEFAULT NULL,
PRIMARY KEY (`webpage_category_id`),
KEY `Fk_User_WebpageCategory_idx` (`deleted_by`),
KEY `Fk_Parent_WebpageCategory_idx` (`parent_id`),
CONSTRAINT `Fk_Parent_WebpageCategory` FOREIGN KEY (`parent_id`) REFERENCES `webpage_category` (`webpage_category_id`) ON DELETE SET NULL ON UPDATE NO ACTION,
CONSTRAINT `Fk_User_WebpageCategory` FOREIGN KEY (`deleted_by`) REFERENCES `user` (`user_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb3;
Since I use soft delete in PHP, I want when a specific webpage category is deleted all rows that have set that webpage category as parent_id,those parent_id fields should be set to null.
I have the following code:
DELIMITER //
CREATE TRIGGER _set_webpage_category_foreign_key_to_null
AFTER UPDATE ON webpage_category
FOR EACH ROW
BEGIN
IF !(NEW.deleted_at <=> OLD.deleted_at) THEN
update webpage_category
set parent_id = NULL
WHERE parent_id = NEW.webpage_category_id;
END IF;
END; //
The error that I get in log file is: Can't update table 'webpage_category' in stored function/trigger because it is already used by statement which invoked this stored function/trigger
Any help will be deeply appreciated.

Related

MySQL error 1022 when inserting. How to fix?

I have very strange problem with my MariaDB Database.
I am using it in pair with gorm
When I try to make an insert request to one of the tables I receive error
Error 1022: Can't write; duplicate key in table 'titles'
Ok. I try to use the same code directly from Navicat or Datagrip and MAGIC - everything is working and record inserting. I have checked foreign keys - all have unique names, but I still don't know how even model this.
Definition of table
/*
Navicat MariaDB Data Transfer
Source Server : My Hetzner
Source Server Version : 100316
Source Host : 127.0.0.1:3306
Source Database : sovet_api
Target Server Type : MariaDB
Target Server Version : 100316
File Encoding : 65001
Date: 2020-05-09 18:46:52
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for titles
-- ----------------------------
DROP TABLE IF EXISTS `titles`;
CREATE TABLE `titles` (
`anime_id` int(11) NOT NULL,
`anime_name` varchar(255) DEFAULT NULL,
`anime_name_rus` varchar(255) DEFAULT NULL,
`ai_help` varchar(255) DEFAULT NULL,
`pidor_ban` int(11) DEFAULT 0,
`vk_new_template_sub` text CHARACTER SET utf8mb4 DEFAULT NULL,
`vk_new_template_dub` text CHARACTER SET utf8mb4 DEFAULT NULL,
`video_name_template_sub` varchar(255) DEFAULT '',
`video_name_template_dub` varchar(255) DEFAULT '',
`video_desc_template_sub` text DEFAULT NULL,
`video_desc_template_dub` text DEFAULT NULL,
`telegram_new_template_sub` text CHARACTER SET utf8mb4 DEFAULT NULL,
`telegram_new_template_dub` text CHARACTER SET utf8mb4 DEFAULT NULL,
`telegram_sub_group_id` bigint(20) DEFAULT -1001269855704,
`telegram_dub_group_id` bigint(20) DEFAULT -1001269855704,
`vk_banned` int(11) DEFAULT 0,
`command_sub_id` int(11) DEFAULT 1,
`command_dub_id` int(11) DEFAULT 1,
`default_preroll_id_sub` int(11) DEFAULT NULL,
`default_watermark_id_sub` int(11) DEFAULT NULL,
`default_preroll_id_dub` int(11) DEFAULT NULL,
`default_watermark_id_dub` int(11) DEFAULT NULL,
`vk_sub_group_id` bigint(20) DEFAULT 33905270,
`vk_dub_group_id` bigint(20) DEFAULT 33905270,
`vk_album_id_sub` int(11) DEFAULT NULL,
`vk_album_id_dub` int(11) DEFAULT NULL,
`repost_sub_vk_group_id` int(11) DEFAULT 0,
`repost_dub_vk_group_id` int(11) DEFAULT 0,
`default_sub_add_att` text DEFAULT NULL,
`default_dub_add_att` text DEFAULT NULL,
`gdrive_parent_id` varchar(255) DEFAULT NULL,
`gdrive_torrent_id` varchar(255) DEFAULT NULL,
`gdrive_sub_id` varchar(255) DEFAULT NULL,
`gdrive_font_id` varchar(255) DEFAULT NULL,
`ai_search_enabled` int(11) DEFAULT 1,
`nyaa_scan_enabled` int(11) DEFAULT 0,
`anime_shiki_id` int(11) DEFAULT NULL,
`anime_name_jpn` varchar(255) DEFAULT NULL,
`anime_rating` varchar(255) DEFAULT NULL,
`anime_episodes` int(255) DEFAULT 0,
`hashtags` text DEFAULT NULL,
`subscribe_sub_enabled` smallint(6) DEFAULT 0,
`subscribe_dub_enabled` smallint(6) DEFAULT 0,
`subscribe_priority` smallint(6) DEFAULT 0,
`sub_purse` bigint(255) DEFAULT NULL,
`dub_purse` bigint(255) DEFAULT NULL,
`sub_qiwi` varchar(255) DEFAULT NULL,
`dub_qiwi` varchar(255) DEFAULT NULL,
`sub_paypal` varchar(255) DEFAULT NULL,
`dub_paypal` varchar(255) DEFAULT NULL,
PRIMARY KEY (`anime_id`),
KEY `command_sub_id` (`command_sub_id`),
KEY `command_dub_id` (`command_dub_id`),
KEY `default_watermark_id_sub` (`default_watermark_id_sub`),
KEY `default_watermark_id_dub` (`default_watermark_id_dub`),
KEY `default_preroll_id_sub` (`default_preroll_id_sub`),
KEY `default_preroll_id_dub` (`default_preroll_id_dub`),
FULLTEXT KEY `IDX__titles__anime_name_search` (`anime_name`,`ai_help`),
FULLTEXT KEY `IDX__titles__anime_name_search_bot` (`anime_name`,`anime_name_rus`,`ai_help`),
CONSTRAINT `titles_ibfk_1` FOREIGN KEY (`command_sub_id`) REFERENCES `command` (`command_id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `titles_ibfk_2` FOREIGN KEY (`command_dub_id`) REFERENCES `command` (`command_id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `titles_ibfk_3` FOREIGN KEY (`default_watermark_id_sub`) REFERENCES `watermarks` (`watermark_id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `titles_ibfk_4` FOREIGN KEY (`default_watermark_id_dub`) REFERENCES `watermarks` (`watermark_id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `titles_ibfk_5` FOREIGN KEY (`default_preroll_id_sub`) REFERENCES `prerolls` (`preroll_id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `titles_ibfk_6` FOREIGN KEY (`default_preroll_id_dub`) REFERENCES `prerolls` (`preroll_id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and
DROP TRIGGER IF EXISTS `trigger_hash_gen`;
DELIMITER ;;
CREATE TRIGGER `trigger_hash_gen` AFTER INSERT ON `titles`
FOR EACH ROW
IF NOT EXISTS (SELECT * FROM title_hashtags
WHERE hashtag_value = TRIM(BOTH '_' FROM
REGEXP_REPLACE(NEW.anime_name, '[^a-zA-Z0-9]+','_')))
THEN
INSERT INTO title_hashtags(anime_id, hashtag_value)
VALUES (NEW.anime_id, TRIM(BOTH '_' FROM
REGEXP_REPLACE(NEW.anime_name, '[^a-zA-Z0-9]+','_')));
END IF
;;
DELIMITER ;
The SQL-code
INSERT INTO `titles` (`anime_id`,`anime_name`,`anime_name_rus`,`pidor_ban`,`vk_new_template_sub`,`vk_new_template_dub`,`video_name_template_sub`,`video_name_template_dub`,`video_desc_template_sub`,`video_desc_template_dub`,`telegram_new_template_sub`,`telegram_new_template_dub`,`telegram_sub_group_id`,`telegram_dub_group_id`,`vk_banned`,`vk_sub_group_id`,`vk_dub_group_id`,`vk_album_id_sub`,`vk_album_id_dub`,`default_sub_add_att`,`default_dub_add_att`,`gdrive_parent_id`,`gdrive_torrent_id`,`gdrive_sub_id`,`gdrive_font_id`,`anime_shiki_id`,`anime_name_jpn`,`anime_rating`,`anime_episodes`,`subscribe_sub_enabled`,`subscribe_dub_enabled`,`subscribe_priority`,`sub_purse`,`dub_purse`,`sub_qiwi`,`dub_qiwi`,`sub_paypal`,`dub_paypal`,`ai_search_enabled`,`nyaa_scan_enabled`)
VALUES ('1046','Urashimasakatasen no Nichijou Special','Деньки Урасимасакатасэн: Школьная пора — Эпизод 13','0','','','','','','','','','0','0','0','0','0','56053731','56053731','','','1-SHGDPX_ybF0Kqu0rtLKcnY_rmfsXa96','1WmRjv8fsZAAY2uBGoRx76Ar1B8rJGKcj','1TvlCnAQ6DbLR3WWiePDCJerYNEwX09oW','1nZRP4Yf92DyuyeOPtW44_vzZLENN6gs6','40921','','','0','0','0','0','0','0','','','','','0','0')
But when I try to use THE SAME SQL in datagrip, navicat or smth other - it works
Thank you!
How about not doing the IF...SELECT; simply do INSERT IGNORE ....
Or maybe INSERT ... ON DUPLICATE KEY UPDATE ...

How to use "ON UPDATE CASCADE" Correctly in MariaDB 10.1.37 / Ver 15.1?

I am experiencing trouble getting ON UPDATE CASCADE to work with a CONSTRAINT. If I use UPDATE to change the value of customerName in the customer table, it will not change the customerName value in the city table. No error message shows up.
The version of the MariaDB:
Ver 15.1 Distrib 10.1.37-MariaDB
My city table when using SHOW CREATE TABLE city:
city | CREATE TABLE `city` (
`cityId` int(10) unsigned NOT NULL AUTO_INCREMENT,
`city` varchar(50) DEFAULT NULL,
`countryId` int(10) unsigned DEFAULT NULL,
`customerName` varchar(50) DEFAULT NULL,
`address` varchar(50) DEFAULT NULL,
`postalCode` varchar(50) DEFAULT NULL,
`phone` varchar(50) DEFAULT NULL,
`createDate` varchar(50) DEFAULT NULL,
`createdBy` varchar(50) DEFAULT NULL,
`lastUpdateBy` varchar(50) DEFAULT NULL,
PRIMARY KEY (`cityId`),
KEY `customerNameChange01` (`customerName`),
CONSTRAINT `customerNameChange01` FOREIGN KEY (`customerName`)
REFERENCES `customer` (`customerName`)
ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
My customer table SHOW CREATE TABLE customer:
customer | CREATE TABLE `customer` (
`customerId` int(10) unsigned NOT NULL AUTO_INCREMENT,
`customerName` varchar(50) DEFAULT NULL,
`addressId` int(10) unsigned DEFAULT NULL,
`active` int(10) unsigned DEFAULT NULL,
`address` varchar(50) DEFAULT NULL,
`city` varchar(50) DEFAULT NULL,
`postalCode` varchar(50) DEFAULT NULL,
`phone` varchar(50) DEFAULT NULL,
`createDate` varchar(50) DEFAULT NULL,
`createdBy` varchar(50) DEFAULT NULL,
`lastUpdateBy` varchar(50) DEFAULT NULL,
PRIMARY KEY (`customerId`),
KEY `CustomerName` (`customerName`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
These are the commands I used to create the index and CONSTRAINT:
CREATE INDEX CustomerName ON customer (customerName);
ALTER TABLE city
ADD CONSTRAINT customerNameChange01
FOREIGN KEY (customerName)
REFERENCES customer (customerName)
ON UPDATE CASCADE
ON DELETE SET NULL;
In the customer table, the CustomerName key references an index. Otherwise, I would not have been able to put in the CONSTRAINT in the city table.
Update: The code works fine in DB Fiddle for MariaDB 10.2 and personal testing confirms that the example code from there works in my own database as well.
Thank you for spending your time.

MySQL Error Number 150 when creating Table with Foreign Key

I am having an issue creating a new table in my database. I've seen that the error code it is returning is to do with Foreign Key constraints.
I checked to ensure that the data type of the foreign key in the new table matched the data type of the primary key in the other table. They are both int(11).
However I am still getting an error. Am I missing something? This is my SQL script for creating the new table:
CREATE TABLE `regular_features` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(200) DEFAULT NULL,
`day` VARCHAR(200) DEFAULT NULL,
`description` TEXT DEFAULT NULL,
`programme_id` INT(11) NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (`programme_id`) REFERENCES directoryprogramme(id)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
This is the original table containing the primary key:
CREATE TABLE `directoryprogramme` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(250) NOT NULL,
`broadcast_time` VARCHAR(100) NOT NULL,
`description` TEXT NOT NULL,
`days` VARCHAR(150) NOT NULL,
`contributors` VARCHAR(250) NOT NULL,
`directorycompany_id` INT(11) NOT NULL,
`directorycontact_id` VARCHAR(250) NOT NULL,
`facebook_link` VARCHAR(250) DEFAULT NULL,
`twitter_link` VARCHAR(250) DEFAULT NULL,
`wikipedia_link` VARCHAR(250) DEFAULT NULL,
`web` VARCHAR(250) DEFAULT NULL,
`imageextension` VARCHAR(10) DEFAULT NULL,
`type` VARCHAR(20) NOT NULL DEFAULT 'other',
PRIMARY KEY (`id`)
) ENGINE=MYISAM AUTO_INCREMENT=1161 DEFAULT CHARSET=utf8;
The Foreign Key will be the id of directoryprogramme
The problem is the last line of your create statement:
ENGINE=INNODB DEFAULT CHARSET=utf8;
You mix MYISAM in ald table with INNODB in your new table.
That doesn't work.
Chnage the engine in your new table to MYISAM and it works.

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row on CONSTRAINT `fk_users_has_ratings_businesses1

I'm getting this error when i try to insert new ratings
Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`yuldi`.`users_ratings`, CONSTRAINT `fk_users_has_ratings_businesses1` FOREIGN KEY (`business_id`) REFERENCES `businesses` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
below database table structure with some foreign keys. i'm confused with adding multiple primary and foreign keys. please help me to sort out this issue
CREATE TABLE IF NOT EXISTS `yuldi`.`businesses` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`state` VARCHAR(100) NOT NULL,
`slug` VARCHAR(250) NOT NULL,
`city` VARCHAR(100) NOT NULL,
`suburb` VARCHAR(100) NOT NULL,
`business_name` VARCHAR(100) NOT NULL,
`business_address` VARCHAR(250) NOT NULL,
`business_postal` VARCHAR(10) NOT NULL,
`business_postal_id` INT(11) NOT NULL,
`business_phone` VARCHAR(50) NOT NULL,
`business_phone1` VARCHAR(50) NOT NULL,
`business_phone2` VARCHAR(50) NOT NULL,
`business_email` VARCHAR(100) NOT NULL,
`business_website` VARCHAR(200) NOT NULL,
`business_details` VARCHAR(5000) NOT NULL,
`business_openinghours` VARCHAR(200) NOT NULL,
`business_service` VARCHAR(200) NOT NULL,
`business_addtionalinfo` VARCHAR(200) NOT NULL,
`business_lat` FLOAT(10,6) NOT NULL,
`business_lng` FLOAT(10,6) NOT NULL,
`identity` VARCHAR(100) NOT NULL,
`status` INT(11) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 232
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `yuldi`.`ratings` (
`id` VARCHAR(36) NOT NULL,
`model` VARCHAR(255) NOT NULL,
`value` FLOAT(8,4) NULL DEFAULT '0.0000',
`comment` TEXT NULL DEFAULT NULL,
`created` DATETIME NULL DEFAULT NULL,
`modified` DATETIME NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `UNIQUE_RATING` (`model` ASC))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `yuldi`.`users` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_email` VARCHAR(255) NULL DEFAULT NULL,
`user_password` CHAR(100) NULL DEFAULT NULL,
`user_name` VARCHAR(255) NULL DEFAULT NULL,
`user_code` VARCHAR(255) NULL DEFAULT NULL,
`user_status` TINYINT(4) NULL DEFAULT '0',
`created` DATETIME NULL DEFAULT NULL,
`modified` DATETIME NULL DEFAULT NULL,
`ip_address` VARCHAR(15) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 14
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `yuldi`.`users_ratings` (
`user_id` INT(11) NOT NULL,
`rating_id` VARCHAR(36) NOT NULL,
`business_id` INT(11) NOT NULL,
PRIMARY KEY (`user_id`, `rating_id`, `business_id`),
INDEX `fk_users_has_ratings_ratings1_idx` (`rating_id` ASC),
INDEX `fk_users_has_ratings_users1_idx` (`user_id` ASC),
INDEX `fk_users_has_ratings_businesses1_idx` (`business_id` ASC),
CONSTRAINT `fk_users_has_ratings_businesses1`
FOREIGN KEY (`business_id`)
REFERENCES `yuldi`.`businesses` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_users_has_ratings_ratings1`
FOREIGN KEY (`rating_id`)
REFERENCES `yuldi`.`ratings` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_users_has_ratings_users1`
FOREIGN KEY (`user_id`)
REFERENCES `yuldi`.`users` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
The problem is coming from this:
CONSTRAINT `fk_users_has_ratings_businesses1`
FOREIGN KEY (`business_id`)
REFERENCES `yuldi`.`businesses` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
The record you're trying to insert / update - probably user_ratings - is foreign keyed to the businesses table; you can't create a user_ratings record without a business_id, and that business_id must actually exist as an id in the businesses table.

cannot add second FK : got error can't create table'.jobstatus\#sql-32c_12f2f.frm' (errno:150)

CREATE TABLE `job` (
`jobId` int(11) NOT NULL auto_increment,
`jobcode` varchar(25) default NULL,
`jobname` varchar(255) default NULL,
`location` varchar(255) default NULL,
`budget` int(10) unsigned default NULL,
`year_type` varchar(100) default NULL,
`worklineId` int(11) default NULL,
PRIMARY KEY (`jobId`),
KEY `NewIndex` (`worklineId`),
FOREIGN KEY (`worklineId`) REFERENCES `workline` (`worklineId`)
) TYPE=InnoDB;
CREATE TABLE `subjob` (
`subjobId` int(11) NOT NULL auto_increment,
`subjobcode` varchar(25) default NULL,
`subjobname` varchar(255) default NULL,
`subjobbudget` int(11) unsigned default NULL,
`jobgoal_date` date default '0000-00-00',
`jobId` int(11) default NULL,
PRIMARY KEY (`subjobId`),
KEY `NewIndex` (`jobId`),
FOREIGN KEY (`jobId`) REFERENCES `job` (`jobId`)
) TYPE=InnoDB;
CREATE TABLE `contract` (
`contractId` int(11) NOT NULL auto_increment,
`contractcode` varchar(25) default NULL,
`price` int(11) unsigned default NULL,
`contractprice` int(11) unsigned default NULL,
`company` varchar(50) default NULL,
`signdate` date default '0000-00-00',
`begindate` date default '0000-00-00',
`enddateplan` date default '0000-00-00',
`note` text,
PRIMARY KEY (`contractId`)
) TYPE=InnoDB;
CREATE TABLE `subjob_contract` (
`subjobcontractId` int(11) NOT NULL auto_increment,
`status` varchar(11) default NULL,
`contractId` int(11) default NULL,
`subjobId` int(11) default NULL,
PRIMARY KEY (`subjobcontractId`),
KEY `NewIndex` (`contractId`),
KEY `NewIndex2` (`subjobId`),
FOREIGN KEY (`contractId`) REFERENCES `contract` (`contractId`)
) TYPE=InnoDB
I m using mysql front 3.2 to manage database,I can add first fk but when i add second fk i got an error following this :
sql execution error #1005. response from the database: can't create table'.jobstatus#sql-32c_12f2f.frm' (errno:150). i already define the new index for fk subjobId reference to subjob table what could be the possibility of this error? thank you
Check the datatype and size of the subjobId column on primary table and referenced table. both must be same than it will allow you to create foreign key.
Answer is: You can not refer that column/table which is not created yet. Try to execute tables having foreign keys after the referenced tables.
Obviously you should have consistency in datatypes of foreign key and referenced column as well
Correct Execution Demo. Also You should use Engine=InnoDB instead of Type=InnoDB