I use MySQL 5.3.28 to create my database. One of the tables is referring itself, which is a big pain. Here is the originally created code:
CREATE TABLE IF NOT EXISTS `dhbpsychiatry`.`activity` (
`ActivityId` INT(11) NOT NULL AUTO_INCREMENT ,
`NeedsRepeating` BINARY(1) NULL DEFAULT NULL ,
`Prerequisition` INT(11) NOT NULL DEFAULT 0 ,
`ActivityName` VARCHAR(45) NOT NULL ,
`ActivityDescription` VARCHAR(45) NULL ,
PRIMARY KEY (`ActivityId`) ,
INDEX `Prerequisition` (`ActivityId` ASC) ,
CONSTRAINT `Prerequisition`
FOREIGN KEY (`ActivityId` )
REFERENCES `dhbpsychiatry`.`activity` (`ActivityId` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
Problem is of course with creating first row.
INSERT INTO `dhbpsychiatry`.`activity` (`ActivityId`, `Prerequisition`,
`ActivityName`) VALUES (1, 1, 'No prerequisition');
returns
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails
Same if I try even simpler
INSERT INTO `dhbpsychiatry`.`activity` (`ActivityName`)
VALUES ('No prerequisition');
I think I've tried all possibilities, making the FK nullable, not nullable, with or without default value...
After digging a bit I've found something that works:
SET FOREIGN_KEY_CHECKS = 0;
Insert into activity (ActivityID, ActivityName) VALUES (0,'No prerequisition');
SET FOREIGN_KEY_CHECKS = 1;
So I created a new SQL script in workbench with those lines.
So I have two questions here:
How I can add the first row without the script?
or if its impossible
2 How can I automatically add this script to be executed whenever I froward engineer the database?
Your indexes and Foreign key definitions are confused. Main issue is that column ActivityId is referencing itself.
Try this:
CREATE TABLE IF NOT EXISTS `dhbpsychiatry`.`activity` (
`ActivityId` INT(11) NOT NULL AUTO_INCREMENT ,
`NeedsRepeating` BINARY(1) NULL DEFAULT NULL ,
`Prerequisition` INT(11) NOT NULL DEFAULT 0 ,
`ActivityName` VARCHAR(45) NOT NULL ,
`ActivityDescription` VARCHAR(45) NULL ,
PRIMARY KEY (`ActivityId`) ,
INDEX `Prerequisition_idx` (`Prerequisition`) , --- changed the index name
--- and the indexed column
CONSTRAINT `Prerequisition_fk` --- changed the constraint name
FOREIGN KEY (`Prerequisition` ) --- main issue !! changed
--- the referencing column
REFERENCES `dhbpsychiatry`.`activity` (`ActivityId`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
Related
On MySQL I have a problem regarding a constraint I'm making on the column "loueur_id" of my vehicle table. I'm trying to make it so when the column location have "disponible" or "en_revision" as value then the value of "loueur_id" become null but if the value of "location" is NULL then "loueur_id" value become the id of the customer who is renting the vehicle
CREATE TABLE IF NOT EXISTS `vehicule` (
`id` int NOT NULL AUTO_INCREMENT,
`typ` int NOT NULL UNIQUE,
`nb` int NOT NULL,
`caract` json NOT NULL,
`location` varchar(20),
`photo` varchar(20) NOT NULL,
`loueur_id` int,
PRIMARY KEY (`id`),
INDEX per_loueur (`loueur_id`),
FOREIGN KEY(`loueur_id`) REFERENCES `client`(`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
ALTER TABLE `vehicule`
ADD CONSTRAINT CK_location CHECK ((`location` in('disponible', 'en_revision')))
ADD CONSTRAINT CK_loueur CHECK (`loueur_id` = CASE WHEN `location` in('disponible', 'en_revision' THEN NULL ELSE `loueur_id` END CASE));
This is what I tried to do but mysql said that I've made a syntax error on my last Check constraint. Can someone help me find the problem's solution please?
It is often simpler to express the constraints with boolean logic rather than with case expressions. I think this does what you want:
alter table `vehicule`
add constraint ck_location check ((location in('disponible', 'en_revision'))),
add constraint ck_loueur check (
(location in('disponible', 'en_revision') and loueur_id is null)
or (location is null and loueur_id is not null)
)
Note that check constraints are available starting MySQL 8.0.16 only. In earlier versions, they are parsed without errors, but not actually enforced.
You can do this with one constraint:
alter table `vehicule`
add constraint ck_vehicule_location_loueur_id
check ( (location in ('disponible', 'en_revision') and loueur_id is null) or
(location is null and loueur_id is not null)
);
This question already has answers here:
how to pass a null value to a foreign key field?
(3 answers)
Closed 6 years ago.
I'm trying to set a NULL value in the deserved_slope_2 column when the user edits the value in a form. Unfortunately this column is a foreign key that links to a primary key (auto increment index) of a column of another table.
When running the request I get:
Error Number: 1452
Cannot add or update a child row: a foreign key constraint fails (`game_skisimulation`.`game_created_lifts`, CONSTRAINT `fk_game_created_lifts_game_created_slopes2` FOREIGN KEY (`deserved_slope_2`) REFERENCES `game_created_slopes` (`id_created_slopes`) ON DE)
UPDATE game_created_lifts SET deserved_slope_2 = '0' WHERE id_created_lifts = '200' LIMIT 1
I've read that this is because the NULL ID doesn't exist in the referred table. Unfortunately it seems that I cannot set NULL either in this column:
A primary key column cannot contain NULL values.
How can I solve this problem?
I want to set NULL in the deserved_slope_2 column (to reset it).
-- Table structure for table game_created_lifts
CREATE TABLE `game_created_lifts` (
`id_created_lifts` int(11) NOT NULL,
`id_player` int(11) NOT NULL,
`deserved_slope_1` int(11) DEFAULT NULL,
`deserved_slope_2` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- RELATIONS FOR TABLE `game_created_lifts`:
-- `deserved_slope_1`
-- `game_created_slopes` -> `id_created_slopes`
-- `deserved_slope_2`
-- `game_created_slopes` -> `id_created_slopes`
-- Table structure for table game_created_slopes
CREATE TABLE `game_created_slopes` (
`id_created_slopes` int(11) NOT NULL,
`id_player` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Setting a value to null in a column that has a foreign key constraint which depends on a unique and not null column in should be pretty straight-forward
UPDATE game_created_lifts SET deserved_slope_2 = NULL WHERE id_created_lifts = '200' LIMIT 1;
Go to SQL Fiddle to see it online.
Test data:
create table a (a int primary key);
create table b (a int references a(a));
insert into a(a) values (1);
insert into b(a) values (1);
update b set a = null;
Query:
select * from b
Result:
(null)
I am having a problem on the creation of my table.
The problem lays with the creation of the foreign key/relation to antoher table.
The internet told me to check the column type and check if it was the same as the column which i was referencing to. and its the same.
Futher solutions the internet gave me didn't work So can anyone please help me?
This is the query :
CREATE TABLE IF NOT EXISTS `finprodb`.`tblproject` (
`prj_id` INT(11) NOT NULL AUTO_INCREMENT ,
`prj_nummer` VARCHAR(45) NOT NULL ,
`prj_omschrijving` TEXT NULL DEFAULT NULL ,
`prj_verkoop_waarde` DECIMAL(20,4) NULL DEFAULT NULL ,
`prj_gereed` TINYINT(4) NULL DEFAULT NULL ,
`prj_bedr_id` INT(11) NOT NULL ,
PRIMARY KEY (`prj_id`) ,
UNIQUE INDEX `prj_id_UNIQUE` (`prj_id` ASC) ,
INDEX `fk_tblproject_tblbedrijf1_idx` (`prj_bedr_id` ASC) ,
CONSTRAINT `fk_tblproject_tblbedrijf1`
FOREIGN KEY (`prj_bedr_id` )
REFERENCES `finprodb`.`tblbedrijf` (`bedr_id` )
ON DELETE SET NULL
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci
ON DELETE SET NULL does not go well with prj_bedr_id INT(11) NOT NULL
Make the column nullable (remove the NOT)
I don't know MYSQL well but in DB2 you can't create a relationship unless there is a unique index on the columns referenced in the parent table.
Is there a unique index on finprodb.tblbedrijf (bedr_id ) ?
I have created several tables with MySQL Workbench and I'm having a problem with Foreign Keys. If I export code below I get an error however if I do not export with foreign keys I do not get an error could you have a look at the code for me.
SQL Code:
DROP TABLE IF EXISTS `mydb`.`users` ;
CREATE TABLE IF NOT EXISTS `mydb`.`users` (
`uuserid` INT NOT NULL AUTO_INCREMENT ,
`ufname` VARCHAR(25) NULL ,
`ulname` VARCHAR(25) NULL ,
`uuname` VARCHAR(45) NULL ,
`upass` CHAR(64) NOT NULL ,
`uemail` VARCHAR(254) NOT NULL ,
`urole` INT NULL DEFAULT 0 ,
PRIMARY KEY (`uuserid`) )
ENGINE = InnoDB;
DROP TABLE IF EXISTS `mydb`.`photos` ;
CREATE TABLE IF NOT EXISTS `mydb`.`photos` (
`pphotoid` INT NOT NULL ,
`pname` VARCHAR(4) NULL ,
`plat` FLOAT(10,6) NULL ,
`plng` FLOAT(10,6) NULL ,
`pflag` DECIMAL(10,0) NULL DEFAULT 0 ,
`pext` VARCHAR(4) NULL ,
`plike` DECIMAL(10,0) NULL DEFAULT 0 ,
PRIMARY KEY (`pphotoid`) ,
CONSTRAINT `uuserid`
FOREIGN KEY ()
REFERENCES `mydb`.`users` ()
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') REFERENCES `mydb`.`users` () ON DELETE NO ACTION ON UPDAT' at line 21
My Database has many more tables but this code also breaks. I have tried to insert this using phpmyadmin.
Here you need to specify the column name
FOREIGN KEY (present_table_column_name)
REFERENCES mydb.users (foriegn_key_column_name)
Try running this script. I build this using your script and ran it in SQLFiddle so I know it works. In order to add a foreign key you have to have a field that will be appropriate. In this example I added a uuserid column in the photos table. This column has a foreign key constraint to the uuserid column in the users table.
DROP TABLE IF EXISTS `mydb`.`users` ;
CREATE TABLE IF NOT EXISTS `mydb`.`users` (
`uuserid` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`ufname` VARCHAR(25) NULL ,
`ulname` VARCHAR(25) NULL ,
`uuname` VARCHAR(45) NULL ,
`upass` CHAR(64) NOT NULL ,
`uemail` VARCHAR(254) NOT NULL ,
`urole` INT NULL DEFAULT 0
) ENGINE = InnoDB;
DROP TABLE IF EXISTS `mydb`.`photos` ;
CREATE TABLE IF NOT EXISTS `mydb`.`photos` (
`pphotoid` INT NOT NULL PRIMARY KEY,
`pname` VARCHAR(4) NULL ,
`plat` FLOAT(10,6) NULL ,
`plng` FLOAT(10,6) NULL ,
`pflag` DECIMAL(10,0) NULL DEFAULT 0 ,
`pext` VARCHAR(4) NULL ,
`plike` DECIMAL(10,0) NULL DEFAULT 0,
`uuserid`INT NOT NULL
) ENGINE = InnoDB;
Alter Table `photos` add constraint foreign key(`uuserid`) references `users`(`uuserid`);
In this example above, I moved the statement that sets the primary keys to the columns themselves rather than creating a statement at the end of the SQL.
I thought it would be a little clearer to show you how to add a foreign key constraint outside of the table creation so you can see what caused the syntax error. You had no column names in your foreign key references. Once added the above code will run perfectly.
You have a syntax error exactly where the error message tells you you have one.
The problem is you don't have you have any fields referenced in your constraint. The form of the CONSTRAINT clause should be like this:
CONSTRAINT `fkuuserid`
FOREIGN KEY `fkuuserid` (some_field_in_this_table)
REFERENCES `mydb`.`users` (uuserid)
ON DELETE NO ACTION
ON UPDATE NO ACTION
I honestly don't even see where you have a logical foreign key on the photos table, as there is no uuserid field present in this table.
I've got a weird problem on a MySQL table. When trying to insert a new row, it says the primary key is duplicate. My primary key is auto incremental and is not set within my query (automatically set by MySQL).
The problem is I get a "Duplicate primary key" error on a key that doesn't even exists (I checked). I solved the problem increasing the current auto_increment value but I can't understand how it happened.
Any help would be great.
Edit
Table creation
CREATE TABLE `articles_mvt` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`ext_article_id` int(5) NOT NULL,
`date_mvt` date NOT NULL,
`qte` float(4,2) NOT NULL,
`in_out` enum('in','out') NOT NULL,
`ext_nateco_id` int(5) NOT NULL,
`ext_agent_id` int(5) NOT NULL COMMENT 'Demandeur',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1647 ;
Problematic query
INSERT INTO articles_mvt (
`ext_article_id`,
`date_mvt`,
`qte`,
`in_out`,
`ext_nateco_id`,
`ext_agent_id`
)
VALUES (
'".$_POST["numArticle"]."',
'".dateSql($_POST["date_mvt"])."',
".$_POST["qte_entier"].".".$_POST["qte_virgule"].",
'".$_POST["in_out"]."',
".$_POST["numNateco"].",
".$_POST["demandeur"]."
)
FYI variables are sanitized earlier in the code ;)
Well i think at that time you did not check auto Inc flag on primary key. So when you try to enter than value 0 is insert in the primary key and for second entry it gives error. like that
ID Value
0 A ok it not give error
0 ff it gives error..
Or you may try to insert a row whose ID is already exist like
ID Value
11 A ok it not give error
11 ff it gives error..