I have created two tables, as shown below:
CREATE TABLE `leiame` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`number` INT(10) NOT NULL,
`title` VARCHAR(100) NOT NULL,
PRIMARY KEY (`id`) )
CREATE TABLE `download` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`id_leiame` INT(10) UNSIGNED NULL,
PRIMARY KEY (`id`),
CONSTRAINT `leia_id_fk` FOREIGN KEY (`id_leiame`)
REFERENCES `leiame` (`id`) ON UPDATE CASCADE )
When I add a null value for id_leiame on download, the following error occurs:
Cannot add or update a child row: a foreign key constraint fails (`bd`.`download`, CONSTRAINT `leia_id_fk` FOREIGN KEY (`id_leiame`) REFERENCES `leiame` (`id`) ON UPDATE CASCADE)
I set the id_leiame as NULL.
What I am missing?
As others pointed out in the comments, based on the statement you're executing, you seem to insert 'null' (i.e. a string containing null) instead of actual NULL, i.e. the absence of a value.
What you need to do is something along the lines of (not proper syntax)
if($leiame == "")
$crud->inserir("name,id_leiame", "'$name',null") << no single quotes!
else
$crud->inserir("name,id_leiame", "'$name','$leiame'")
Related
I tried to excute the query. but a error was occurred. the error message is 'Cannot add foreign key constraint'.
I supposed to create this table. but it didn't work.
CREATE TABLE IF NOT EXISTS `mydb`.`member` (
`idseq` INT(1) NOT NULL AUTO_INCREMENT,
`id` VARCHAR(50) NOT NULL,
`pw` VARCHAR(20) NOT NULL,
`name` VARCHAR(50) NOT NULL,
`email` VARCHAR(45) NOT NULL,
`mobile0` VARCHAR(3) NOT NULL,
`mobile1` VARCHAR(3) NOT NULL,
`mobile2` VARCHAR(4) NOT NULL,
`mobile3` VARCHAR(4) NOT NULL,
`birth` DATE NOT NULL,
`admin_YN` VARCHAR(45) NOT NULL DEFAULT 'N',
`reg_date` DATE NOT NULL,
`upd_date` DATE NOT NULL,
PRIMARY KEY (`idseq`, `id`))
ENGINE = InnoDB
AUTO_INCREMENT = 6
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `mydb`.`reservation` (
`reservation_seq` INT(11) NOT NULL AUTO_INCREMENT,
`user_id` VARCHAR(50) NOT NULL,
`playMv_seq` INT(11) NOT NULL,
`reservaion_seat_code` VARCHAR(20) NOT NULL,
`reservaion_seat_num` INT(11) NOT NULL,
`reservation_charge` VARCHAR(20) NOT NULL,
`reservation_date` DATETIME NOT NULL,
PRIMARY KEY (`reservation_seq`, `user_id`, `playMv_seq`),
FOREIGN KEY (`user_id`)
REFERENCES `mydb`.`member` (`id`)
)
ENGINE = InnoDB
AUTO_INCREMENT = 8
DEFAULT CHARACTER SET = utf8;
So I checked it detail from a query'show engine innodb status. the detail error message is
Error in foreign key constraint of table mydb/reservation:
FOREIGN KEY (`user_id`)
REFERENCES `mydb`.`member` (`id`)
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
how can I resolve the error
You're trying to create a foreign key referencing the id column of the target table:
FOREIGN KEY (`user_id`)
REFERENCES `mydb`.`member` (`id`)
But what is the actual key on that target table?:
PRIMARY KEY (`idseq`, `id`)
It's not id, if the composite of idseq and id. In order to reference that as a foreign key, you need local columns which match that:
`user_idseq` INT(1) NOT NULL,
`user_id` VARCHAR(50) NOT NULL,
And use both of them for the foreign key:
FOREIGN KEY (`user_idseq`, `user_id`)
REFERENCES `mydb`.`member` (`idseq`, `id`)
(Side Note: That primary key in member looks pretty strange to me in the first place. Why can't idseq by itself be the primary key? What is the purpose of id?)
CREATE TABLE `class` (
`class_id` int(11) NOT NULL AUTO_INCREMENT,
`section_name` varchar(50) NOT NULL,
`class_alias` varchar(200) NOT NULL,
`grading_scheme` int(11) NOT NULL DEFAULT '0',
`year` year(4) NOT NULL,
`grade_calc_method_id` varchar(20) DEFAULT NULL,
PRIMARY KEY (`class_id`)
) ENGINE=InnoDB AUTO_INCREMENT=48819 DEFAULT CHARSET=latin1;
CREATE TABLE `teachers` (
`teacher_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`teacher_subject` varchar(20) NOT NULL DEFAULT 'None',
PRIMARY KEY (`teacher_id`),
KEY `user_id` (`user_id`,`school_id`)
) ENGINE=InnoDB AUTO_INCREMENT=48606 DEFAULT CHARSET=latin1;
CREATE TABLE `teacher_classes` (
`teacher_class_id` int(11) NOT NULL AUTO_INCREMENT,
`teacher_id` int(11) NOT NULL,
`class_id` int(11) NOT NULL,
PRIMARY KEY (`teacher_class_id`),
UNIQUE KEY `teacher_id_class_id` (`teacher_id`,`class_id`),
KEY `teacher_id` (`teacher_id`,`class_id`)
) ENGINE=InnoDB AUTO_INCREMENT=46707 DEFAULT CHARSET=latin1;
Trying to insure data consistency between the tables by using foreign key so that the DBMS can check for errors.I have another junction table teacher_classes
Here is my query to add foreign keys constraint
ALTER TABLE teacher_classes
ADD CONSTRAINT `tc_fk_class_id` FOREIGN KEY (`class_id`)
REFERENCES class (`class_id`) ON UPDATE NO ACTION ON DELETE NO ACTION,
ADD CONSTRAINT `tc_fk_teacher_id` FOREIGN KEY (`teacher_id`)
REFERENCES teachers (`teacher_id`) ON UPDATE NO ACTION ON DELETE NO ACTION;
've seen the other posts on this topic, but no luck, getting following error.
Cannot add or update a child row: a foreign key constraint fails
(DB_NAME.#sql-403_12, CONSTRAINT
tc_fk_teacher_id FOREIGN KEY (teacher_id) REFERENCES teachers
(teacher_id) ON DELETE NO ACTION ON UPDATE NO ACTION)
Too late to Answer. I just had the same problem the solution is easy.
You're getting this error because you're trying to or UPDATE a row to teacher_classes doesn't match the id in table teachers.
A simple solution is disable foreign key checks before performing any operation on the table.
SET FOREIGN_KEY_CHECKS = 0;
After you are done with the table enable it again.
SET FOREIGN_KEY_CHECKS = 1;
Or you can remove not null constraint and insert a NULL value in it.
That's most probably the column definition doesn't match properly. For table teachers the PK column definition is as below.
`teacher_id` int(11) NOT NULL AUTO_INCREMENT
Make sure you have the same definition in your child table teacher_classes
What is the right way to assign primary key with shortcut query while creating table?
Here is the example how my shortcut it is:
create table booking_product (
`id` int(10) not null constraint `booking_product_id` primary key auto_increment ,
`bookingId` int(10) not null,
`serviceId` int(10) not null,
`date` date not null,
`price` decimal(30,15) not null,
`qty` int(1) not null,
`currencyId` int(10) not null,
`total` decimal(30,15) not null,
`roomInclusion` text null default null,
foreign key booking_product(bookingId) references booking(id) on update cascade on delete cascade,
foreign key booking_product(serviceId) references service(id) on update cascade on delete set null,
foreign key booking_product(currencyId) references currency(id) on update cascade on delete set null
) engine = InnoDB;
notice on line 2 I tried to assign primary key, but this query is wrong and produce error. If I try to only use id int(10) not null primary key auto_increment , I get error: Duplicate key name 'booking_product'
If you use constraint booking_product_id, you don't get errors about Duplicate key name 'booking_product' because the SQL parser stops at the first error.
Drop constraint booking_product_id and use
foreign key bookingId_fk(bookingId) references booking(id)
on update cascade
on delete cascade,
foreign key serviceId_fk(serviceId) references service(id)
on update cascade
on delete set null,
foreign key currencyId_fk(currencyId) references currency(id)
on update cascade
on delete set null
I know you picked an answer but when I simplified just your create statement to the code below I got it to work. Now with the added 'drop constraint' request by Oswald you might have everything you want:
create table booking_product (
id int(10) not null auto_increment,
PRIMARY KEY(id), <<<<< this worked for me...
bookingId int(10) not null,
serviceId int(10) not null,
date date not null,
price decimal(30,15) not null,
qty int(1) not null,
currencyId int(10) not null,
total decimal(30,15) not null,
roomInclusion text null default null)
Again I am only approaching the question from what you asked which was assigning a primary.
Hope this helps.
I have a table with a compound primary key "name" and "id". The fields are actually "name","id","phone","amount","units","alias". I have the query
insert into MyTable (name,id,phone,amount) select "henry" as name, id,phone,amount from anotherTable
on duplicate key update phone=values(phone),amount=values(amount).
MySQL spits the following error:
Cannot add or update a child row: a foreign key constraint fails.
BTW, "id" is a foreign key.
Any help?
as requested below, the schema for other table is
CREATE TABLE `otherTable` (
`otherId` int(11) NOT NULL AUTO_INCREMENT,
`DOBId` int(11) NOT NULL,
`bankAccount` int(11) DEFAULT NULL,
`partialAmount` int(11) NOT NULL DEFAULT '0',
`id` int(11) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`notes` varchar(299) DEFAULT NULL,
`latitude` decimal(8,5) DEFAULT NULL,
`longitude` decimal(8,5) DEFAULT NULL,
PRIMARY KEY (`otherId `),
KEY `DOBId ` (`DOBId `),
KEY `bankAccount ` (`bankAccount `),
KEY `id ` (`id `)
) ENGINE=InnoDB AUTO_INCREMENT=3305 DEFAULT CHARSET=utf8;
for myTable
CREATE TABLE `myTable` (
`name` int(11) NOT NULL,
`id` int(11) NOT NULL,
`appleNumber` int(11) DEFAULT NULL,
`amount` int(11) DEFAULT NULL,
`windowsNumber` int(11) DEFAULT NULL,
`phone` int(11) DEFAULT NULL,
`pens` int(11) DEFAULT NULL,
`pencils` int(11) DEFAULT NULL,
PRIMARY KEY (`name`,`id`),
KEY `id` (`id`),
CONSTRAINT `myTable_ibfk_1` FOREIGN KEY (`id`) REFERENCES `yet_another` (`id`)
The problem appears to be that the FK constraint you have on myTable is referencing the ids of yet_another, so when you are inserting ids from anotherTable you are breaking this FK constraint. Chances are there are ids in anotherTable that do not exist in yet_another table.
Understand this is a shot in the dark, based on the abstracted schema you posted. If you want a more solid answer, I'd have to see the actual schema.
The on duplicate key applies to the primary key. I take it you're using innodb. This is failing on a foreign key constraint. Which values of you table MyTable are foreign keys? Please post the create statement for the table that shows all keys and constraints for more detailed help.
Just a guess, but for grins I'm betting it's a column that's not in the insert that is a foreign key not allowing a null value.
I am working on a project that makes use of a MySQL Database to store snippets of code for use on multiple websites. For each content snippet I also keep an edit history table, to which I add a record every time a snippet is updated. Occasionally it will be desirable to delete a snippet completely, and any associated edit history. When setting up the DB, I set up the foreign key relationship to ON DELETE CASCADE so that deleting the snippet will automatically delete the history. However, I am getting the following error:
Error in query: delete from SNIPPET where id = 1. Cannot delete or update a parent row: a foreign key constraint fails (universal_content_repository/SNIPPET_EDIT_HISTORY, CONSTRAINT fk_SNIPPET_EDIT_HISTORYRelationship13 FOREIGN KEY (snippet_id) REFERENCES SNIPPET (id))
Here is the code I use to create the DB as well as the relationships:
/*Schema universal_content_repository*/
CREATE SCHEMA IF NOT EXISTS `universal_content_repository`
DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `universal_content_repository`;
CREATE TABLE `universal_content_repository`.`USER` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Stores the ID for the User.',
`username` VARCHAR(20) NOT NULL,
`first_name` VARCHAR(32) NOT NULL,
`last_name` VARCHAR(32) NOT NULL,
`is_active` VARCHAR(5) NOT NULL DEFAULT true,
`password` VARCHAR(32) NOT NULL,
`is_admin` BIT NOT NULL DEFAULT 0,
`prefers_wysiwyg` BIT DEFAULT 0,
PRIMARY KEY (`id`)
) COMMENT 'Stores information about all Users for the Universal Content Repository.' ENGINE=INNODB
ROW_FORMAT=DEFAULT;
CREATE TABLE `universal_content_repository`.`SNIPPET` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`title` VARCHAR(255) NOT NULL,
`content` TEXT NOT NULL,
`created_by` INT UNSIGNED,
`wysiwyg_editable` VARCHAR(6) NOT NULL DEFAULT true,
`is_enabled` BIT NOT NULL DEFAULT 1,
PRIMARY KEY (`id`)
) COMMENT 'Guarantees that no two snippets may have the same name or ID.' ENGINE=INNODB
ROW_FORMAT=DEFAULT;
CREATE TABLE `universal_content_repository`.`IMAGE` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(32) NOT NULL,
`url` TEXT NOT NULL,
`alt` VARCHAR(32),
PRIMARY KEY (`id`)
) ENGINE=INNODB
ROW_FORMAT=DEFAULT;
CREATE TABLE `universal_content_repository`.`IMAGE_IN_SNIPPET` (
`rel_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`snippet_id` INT UNSIGNED,
`image_id` INT UNSIGNED,
`position` INT COMMENT 'Stores the position of the image within the snippet, as notated in the snippet as [index]',
PRIMARY KEY (`rel_id`)
) ENGINE=INNODB
ROW_FORMAT=DEFAULT;
CREATE TABLE `universal_content_repository`.`SNIPPET_EDIT_HISTORY` (
`revision_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`editing_user` INT UNSIGNED,
`snippet_id` INT UNSIGNED,
`old_contents` TEXT NOT NULL COMMENT 'Stores the old contents of the snippet.',
`edit_date` DATETIME NOT NULL COMMENT 'Stores the DateTime of the edit.',
PRIMARY KEY (`revision_id`)
) ENGINE=INNODB
ROW_FORMAT=DEFAULT;
CREATE TABLE `universal_content_repository`.`SESSION` (
`id` VARCHAR(32) NOT NULL COMMENT 'Stores the Session ID',
`access` INT(10) UNSIGNED NOT NULL,
`data` TEXT,
PRIMARY KEY (`id`)
) ENGINE=INNODB
ROW_FORMAT=DEFAULT;
ALTER TABLE `universal_content_repository`.`USER` ADD UNIQUE `Identifiers` (`id`,`username`);
ALTER TABLE `universal_content_repository`.`SNIPPET` ADD UNIQUE `identifiers` (`title`,`id`);
ALTER TABLE `universal_content_repository`.`SNIPPET` ADD CONSTRAINT `fk_SNIPPETRelationship8` FOREIGN KEY (`created_by`) REFERENCES `universal_content_repository`.`USER`(`id`) MATCH SIMPLE ON UPDATE RESTRICT ON DELETE RESTRICT;
ALTER TABLE `universal_content_repository`.`IMAGE_IN_SNIPPET` ADD CONSTRAINT `fk_IMAGE_IN_SNIPPETRelationship10` FOREIGN KEY (`snippet_id`) REFERENCES `universal_content_repository`.`SNIPPET`(`id`) MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE;
ALTER TABLE `universal_content_repository`.`IMAGE_IN_SNIPPET` ADD CONSTRAINT `fk_IMAGE_IN_SNIPPETRelationship11` FOREIGN KEY (`image_id`) REFERENCES `universal_content_repository`.`IMAGE`(`id`) MATCH SIMPLE ON UPDATE RESTRICT ON DELETE RESTRICT;
ALTER TABLE `universal_content_repository`.`SNIPPET_EDIT_HISTORY` ADD CONSTRAINT `fk_SNIPPET_EDIT_HISTORYRelationship12` FOREIGN KEY (`editing_user`) REFERENCES `universal_content_repository`.`USER`(`id`) MATCH SIMPLE ON UPDATE RESTRICT ON DELETE RESTRICT;
ALTER TABLE `universal_content_repository`.`SNIPPET_EDIT_HISTORY` ADD CONSTRAINT `fk_SNIPPET_EDIT_HISTORYRelationship13` FOREIGN KEY (`snippet_id`) REFERENCES `universal_content_repository`.`SNIPPET`(`id`) MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE;
If you want to see a graphical representation of the DB, you can see it at SchemaBank.
For those without a SchemaBank account, here is the ER:
Any ideas?
Looks like your code is right.
If it's practical, dump that database and restore it onto a different server as a test. If INNODB and MySQL internal states have gotten out of sync, that should give you a well-behaved database on the server you restore to.