I'm writing a script for an associative table in MySQL and It stops compiling at the second foreign key constraint; does anyone know what could be wrong? Please, I would appreciate it!
create table Adviser(
AdviserID integer not null,
LastName char(25) not null,
FirstName char(25) not null,
AdviserEmail varchar(100) not null,
OfficePhoneNumber char(12) not null,
constraint Adviser_pk primary key(AdviserID),
constraint Adviser_fk foreign key(OfficePhoneNumber)
references Department(OfficePhoneNumber)
on delete no action
on update no action
);
create table Student(
StudentID integer not null,
LastName char(25) not null,
FirstName char(25) not null,
StudentEmail varchar(100) not null,
EnrollmentDate date not null,
GradDate date not null,
Degree char(25) not null,
DormPhoneNumber char(12) not null,
constraint Student_pk primary key(StudentID),
constraint Student_fk foreign key(DormPhoneNumber)
references Dorm(DormPhoneNumber)
on delete no action
on update no action
);
The two tables above work fine, when I make the table below link to the two above something goes wrong with having 2 foreign keys
create table AppointmentDate1(
AdviserID integer not null,
StudentID integer not null,
StudentAppointmentDate date not null,
StudentEndDate date not null,
constraint AppointmentDate1_pk primary key(AdviserID, StudentID),
constraint AppointmentDate1_fk foreign key(AdviserID)
references Adviser(AdviserID)
on delete no action
on update no action,
constraint AppointmentDate1_fk foreign key(StudentID)
references Student(StudentID)
on delete no action
on update no action
);
Can anyone help?
Foreign keys need to have different constraint names. Try this:
create table AppointmentDate1(
AdviserID integer not null,
StudentID integer not null,
StudentAppointmentDate date not null,
StudentEndDate date not null,
constraint AppointmentDate1_pk primary key(AdviserID, StudentID),
constraint fk_AppointmentDate1_AdviserId foreign key(AdviserID)
references Adviser(AdviserID)
on delete no action
on update no action,
constraint fk_AppointmentDate1_StudentId foreign key(StudentID)
references Student(StudentID)
on delete no action
on update no action
);
Just rename two foreign keys, it should work just as below..
I tested it using the following create table script on my local database and I could create AppointmentDate1 table successfully.
create table AppointmentDate1(
AdviserID integer not null,
StudentID integer not null,
StudentAppointmentDate date not null,
StudentEndDate date not null,
constraint AppointmentDate1_pk primary key(AdviserID, StudentID),
constraint AdviserId1_fk foreign key(AdviserID)
references Adviser(AdviserID)
on delete no action
on update no action,
constraint StudentId1_fk foreign key(StudentID)
references Student(StudentID)
on delete no action
on update no action
);
Related
I have created tables in MYSQL as follows
Author Table
CREATE TABLE `author` (
`AuthorId` varchar(25) NOT NULL,
`AuthorName` varchar(50) NOT NULL,
PRIMARY KEY (`AuthorId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Books Table
CREATE TABLE `books` (
`DocId` int(11) NOT NULL,
`ISBN` varchar(13) NOT NULL,
PRIMARY KEY (`DocId`),
KEY `DocId` (`DocId`),
CONSTRAINT `books_ibfk_1` FOREIGN KEY (`DocId`) REFERENCES `document`
(`DocId`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Document Table
CREATE TABLE `document` (
`DocId` int(11) NOT NULL,
`Title` varchar(50) NOT NULL,
`PublishDate` date DEFAULT NULL,
`AuthorId` varchar(10) DEFAULT NULL,
`DocType` varchar(10) DEFAULT NULL,
PRIMARY KEY (`DocId`),
KEY `AuthorId` (`AuthorId`),
CONSTRAINT `document_ibfk_3` FOREIGN KEY (`AuthorId`) REFERENCES `author`
(`AuthorId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
I made a server for my PHP website on XAMPP and am using mysql but when I try inserting the values in Document table I get
error while inserting the recordsCannot add or update a child row: a foreign
key constraint fails (`librarydb`.`document`, CONSTRAINT `document_ibfk_3`
FOREIGN KEY (`AuthorId`) REFERENCES `author` (`AuthorId`))
How do I resolve this issue?
Your linked fields author.AuthorId and document.AuthorId are not defined the same way.
From the docs:
Corresponding columns in the foreign key and the referenced key must
have similar data types. The size and sign of integer types must be
the same. The length of string types need not be the same.
So make them both varchar(10) NOT NULL - or whatever you need.
My code runs in phpmyadmin but the foreign key values are not showing in table and when I update it the message shows "0 rows affected"
my table schema is:
CREATE TABLE fee_report (
fr_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
school_id INT NOT NULL,
branch_id INT NOT NULL,
student_id INT NOT NULL,
ledger VARCHAR(55),
bill_no VARCHAR(255) NOT NULL,
fdate date NOT NULL,
receipt_no VARCHAR(255) NOT NULL,
dr float NOT NULL,
cr float NOT NULL,
balance float NOT NULL,
particulars VARCHAR(155),
updated TIMESTAMP NOT NULL,
CONSTRAINT fk_frschool FOREIGN KEY (school_id)
REFERENCES school(school_id),
CONSTRAINT fk_frbranch FOREIGN KEY (branch_id)
REFERENCES branch(branch_id),
CONSTRAINT fk_frstudent FOREIGN KEY (student_id)
REFERENCES student(student_id)
) ENGINE = INNODB;
INSERT INTO fee_report(school_id,branch_id,student_id,ledger,bill_no,fdate,dr,balance,particulars,feetype)
VALUES(1,1,13,'TGS007','SESNOV1020',CURDATE(),'2850','-14450','11','Tuition Fee,Transport Fee,Smart Class Fee,SA-1 Exam Fee')
Why foreign keys school_id, branch_id and student_id are not showing in table
and when I remove foreign key constraint the values are visible in table
I have 3 tables called book , author, publisher. The relationship between book and author is a resolving table called book_author_link. The main issue is that when a user adds a book, it was not successfully added as some of the fields belonged in multiple tables. Therefore I am currently having trouble with the INSERT query. How do I go about doing this?
Here is my PHP:
$queryInsert = "INSERT INTO book,author,
publishers(title,isbn,author_name,publisher_name,year_published, book_desc,genre_id,keywords)
FROM book b, author a ,book_author_link ba, publishers p
VALUES ('$title',$isbn,'$author_name','$publisher_name',$year_published,'$genre_type','$book_desc','$genre_id','$keywords')
WHERE b.book_id = ba.book_id AND a.author_id = ba.author_id AND b.publisher_id = p.publisher_id";
Here is my book table:
CREATE TABLE IF NOT EXISTS `fyp`.`book` (
`book_id` INT NOT NULL AUTO_INCREMENT,
`title` VARCHAR(45) NOT NULL,
`ISBN` VARCHAR(45) NOT NULL,
`book_desc` VARCHAR(100) NOT NULL,
`year_published` VARCHAR(45) NOT NULL,
`year_of_birth` YEAR NOT NULL,
`image` VARCHAR(45) NULL,
`genre_id` INT NOT NULL,
`publisher_id` INT NOT NULL,
`user_id` INT NOT NULL,
PRIMARY KEY (`book_id`),
INDEX `fk_book_publishers1_idx` (`publisher_id` ASC),
INDEX `fk_book_user1_idx` (`user_id` ASC),
INDEX `fk_book_genre1_idx` (`genre_id` ASC),
CONSTRAINT `book_publishers_key`
FOREIGN KEY (`publisher_id`)
REFERENCES `fyp`.`publishers` (`publisher_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `book_user_key`
FOREIGN KEY (`user_id`)
REFERENCES `fyp`.`user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `book_genre_key`
FOREIGN KEY (`genre_id`)
REFERENCES `fyp`.`genre` (`genre_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- Table fyp.author
CREATE TABLE IF NOT EXISTS `fyp`.`author` (
`author_id` INT NOT NULL AUTO_INCREMENT,
`author_name` VARCHAR(45) NOT NULL,
`year_of_birth` YEAR NOT NULL,
`year_deceased` YEAR NULL,
`image` VARCHAR(45) NULL,
`user_id` INT NOT NULL,
`country_id` INT NOT NULL,
`gender_id` INT NOT NULL,
PRIMARY KEY (`author_id`),
INDEX `fk_author_user1_idx` (`user_id` ASC),
INDEX `fk_author_country1_idx` (`country_id` ASC),
INDEX `fk_author_gender1_idx` (`gender_id` ASC),
CONSTRAINT `author_user_key`
FOREIGN KEY (`user_id`)
REFERENCES `fyp`.`user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `author_country_key`
FOREIGN KEY (`country_id`)
REFERENCES `fyp`.`country` (`country_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `author_gender_key`
FOREIGN KEY (`gender_id`)
REFERENCES `fyp`.`gender` (`gender_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- Table fyp.publishers
DROP TABLE IF EXISTS `fyp`.`publishers` ;
CREATE TABLE IF NOT EXISTS `fyp`.`publishers` (
`publisher_id` INT NOT NULL,
`publisher_name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`publisher_id`))
ENGINE = InnoDB;
-- Table fyp.book_author_link
DROP TABLE IF EXISTS fyp.book_author_link ;
CREATE TABLE IF NOT EXISTS `fyp`.`book_author_link` (
`book_author_link_id` INT NOT NULL AUTO_INCREMENT,
`book_id` INT NOT NULL,
`author_id` INT NOT NULL,
PRIMARY KEY (`book_author_link_id`),
INDEX `fk_book_author_link_book_idx` (`book_id` ASC),
INDEX `fk_book_author_link_author1_idx` (`author_id` ASC),
CONSTRAINT `book_key`
FOREIGN KEY (`book_id`)
REFERENCES `fyp`.`book` (`book_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `author_key`
FOREIGN KEY (`author_id`)
REFERENCES `fyp`.`author` (`author_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
I recommend running the queries in a transaction: http://php.net/manual/pdo.transactions.php
Also, you might need this to get the AUTO_INCREMENT id: http://php.net/manual/de/pdo.lastinsertid.php
Are you using phpMyAdmin as GUI? Have you tried running your SQL there? If there is a "relationship issue", it should print the exact error message. You should provide it here.
you could give a try to a trigger AFTER INSERT on the main table.
the berita_ukm table
CREATE TABLE `berita_ukm` (
`id_berita` int(11) NOT NULL AUTO_INCREMENT,
`id_admin` int(11) DEFAULT NULL,
`judul_berita` varchar(45) DEFAULT NULL,
`content` varchar(225) DEFAULT NULL,
`tanggal` date DEFAULT NULL,
PRIMARY KEY (`id_berita`),
FOREIGN KEY (`id_admin`) REFERENCES `admin` (`id_admin`)
)
admin table
CREATE TABLE `berita_ukm` (
`id_admin` int(11) NOT NULL AUTO_INCREMENT,
`name` int(11) DEFAULT NULL,
PRIMARY KEY (`id_admin`),
)
and i found error like this
Error Number: 1452
Cannot add or update a child row: a foreign key constraint fails
(`tugas_akhir`.`berita_ukm`, CONSTRAINT `berita_ukm_ibfk_1`
FOREIGN KEY (`id_admin`) REFERENCES `admin` (`id_admin`))
INSERT INTO `berita_ukm`
(`id_berita`, `tanggal`, `judul_berita`, `content`)
VALUES ('34', '3/25/2014', 'putri', 'nfdn')
please help me what to do. thank you
I guess you misplaced the col names in your insert("id_berita" in place of "id_admin" ), since col "id_berita" is auto increment, you don't need to provide value for that col during insert.
INSERT INTO `berita_ukm`
(`id_admin`, `tanggal`, `judul_berita`, `content`)
VALUES ('34', '3/25/2014', 'putri', 'nfdn')
I built a PHP web app with the Yii framework, using a postgresql db.
Here are my tables apresentante, veiculo, ferro and lavagem:
CREATE TABLE apresentante
(
id serial NOT NULL,
nome character varying(50) NOT NULL,
morada character varying(50),
cp character varying(15),
nif integer NOT NULL,
telefone integer,
telemovel integer,
codigo integer NOT NULL,
CONSTRAINT apresentante_pkey PRIMARY KEY (id)
)
WITHOUT OIDS;
CREATE TABLE veiculo
(
id serial NOT NULL,
matricula character varying(20) NOT NULL,
classe character varying(10) NOT NULL,
CONSTRAINT id_veiculo PRIMARY KEY (id)
)
WITHOUT OIDS;
CREATE TABLE lavagem
(
id serial NOT NULL,
veiculo_id serial NOT NULL,
data date NOT NULL,
apresentante_id smallint NOT NULL,
ferro_id serial NOT NULL,
apresentante_paga boolean NOT NULL,
CONSTRAINT id_lavagem_pkey PRIMARY KEY (id),
CONSTRAINT id_apresentante_fk FOREIGN KEY (apresentante_id)
REFERENCES apresentante (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT id_ferro_fk FOREIGN KEY (ferro_id)
REFERENCES ferro (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT id_veiculo_fk FOREIGN KEY (veiculo_id)
REFERENCES veiculo (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITHOUT OIDS;
CREATE TABLE ferro
(
id serial NOT NULL,
ferro integer NOT NULL,
nome character varying(50) NOT NULL,
CONSTRAINT id_ferro PRIMARY KEY (id)
)
WITHOUT OIDS;
I created the models and forms with Gii.
The problem is that when I try to insert a row into table lavagem it doesn't get the selected FK value, instead it increments the FK values to values that doesn't exist in the FK table.
The exception error:
CDbException
CDbCommand failed to execute the SQL statement: SQLSTATE[23503]: Foreign key violation: 7 ERROR: insert or update on table "lavagem" violates foreign key constraint "id_ferro_fk"
DETAIL: Key (ferro_id)=(4) is not present in table "ferro".. The SQL statement executed was: INSERT INTO "lavagem" ("data", "apresentante_id", "apresentante_paga") VALUES (:yp0, :yp1, :yp2)
Thank you
You've an error in your schema. Foreign keys like:
veiculo_id serial NOT NULL,
Should actually look more like:
veiculo_id int NOT NULL,
It's the id field in the original table that needs to be an auto-incrementing integer; rather than the field that is referencing it.