I want to CREATE 4 tables that has FOREIGN KEYS of each other.
table students :
CREATE TABLE students
(
PRIMARY KEY (student_id),
student_id SERIAL,
student_name VARCHAR(100),
student_age INT,
entry_year INT,
graduate_year INT,
faculty_name VARCHAR(100),
group_id INT,
FOREIGN KEY (group_id) REFERENCES groups(group_id)
);
table groups :
CREATE TABLE groups
(
PRIMARY KEY (group_id),
group_id SERIAL,
group_name VARCHAR(100),
student_id INT,
FOREIGN KEY (student_id) REFERENCES students(student_id)
);
table lessons :
CREATE TABLE lessons
(
PRIMARY KEY (lesson_id),
lesson_id SERIAL,
lesson_name VARCHAR(100),
class_number INT,
date TIMESTAMP,
teacher_id INT,
group_id INT,
FOREIGN KEY(teacher_id) REFERENCES teachers(teacher_id),
FOREIGN KEY (group_id) REFERENCES groups(group_id)
);
table teachers :
CREATE TABLE teachers
(
PRIMARY KEY (teacher_id),
teacher_id INT,
teacher_name VARCHAR(100),
position VARCHAR(100)
);
And when I run this query in Java application, I gain an error with creation table students :
nested exception is org.postgresql.util.PSQLException: ERROR: relation "groups" does not exist
I know why It exception throwed.
Because I am creating table students with foreign key from table groups which has not yet been created.
But I have no idea how to fix It. Thanks in advance for response!
CREATE TABLE students
(
PRIMARY KEY (student_id),
student_id SERIAL,
student_name VARCHAR(100),
student_age INT,
entry_year INT,
graduate_year INT,
faculty_name VARCHAR(100),
group_id INT,
CONSTRAINT fk_group
FOREIGN KEY(group_id)
REFERENCES groups(group_id)
);
https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-foreign-key/
Related
I would like to seek your insights regarding the error I'm encountering with my postgresql commands.
Basically, what I want to achieve is to create a "booking" entity with one to one relationship to another table called "booking details". But flyway won't migrate my schema with the following error:
Caused by: org.flywaydb.core.internal.sqlscript.FlywaySqlScriptException:
Migration V0__Initial.sql failed
--------------------------------
SQL State : 42S02
Error Code : 42102
Message : Table "BOOKING_DETAILS" not found; SQL statement:
ALTER TABLE booking ADD CONSTRAINT FK_BOOKING_ON_BOOKING_DETAILS FOREIGN KEY (booking_details_id) REFERENCES booking_details (booking_entity_id) [42102-214]
Line : 16
Statement : ALTER TABLE booking ADD CONSTRAINT FK_BOOKING_ON_BOOKING_DETAILS FOREIGN KEY (booking_details_id) REFERENCES booking_details (booking_entity_id)
Here is my postgresql commands:
DROP SEQUENCE IF EXISTS booking_transaction_sequence;
DROP TABLE IF EXISTS booking;
CREATE SEQUENCE IF NOT EXISTS booking_transaction_sequence START WITH 1000 INCREMENT BY 100;
CREATE TABLE booking (
id BIGINT NOT NULL,
booking_number VARCHAR(255),
booking_status VARCHAR(255),
processed_by VARCHAR(255),
created_at TIMESTAMP WITHOUT TIME ZONE,
booking_details_id BIGINT,
CONSTRAINT pk_booking PRIMARY KEY (id)
);
ALTER TABLE booking ADD CONSTRAINT FK_BOOKING_ON_BOOKING_DETAILS FOREIGN KEY (booking_details_id) REFERENCES booking_details (booking_entity_id);
DROP SEQUENCE IF EXISTS booking_details_transaction_sequence;
DROP TABLE IF EXISTS booking_details;
CREATE SEQUENCE IF NOT EXISTS booking_details_transaction_sequence START WITH 1000 INCREMENT BY 100;
CREATE TABLE booking_details (
booking_entity_id BIGINT NOT NULL,
sender_name VARCHAR(255),
item_details VARCHAR(255),
pickup_address VARCHAR(255),
rider_name VARCHAR(255),
delivery_address VARCHAR(255),
cancellation_reason VARCHAR(255),
CONSTRAINT pk_booking_details PRIMARY KEY (booking_entity_id)
);
ALTER TABLE booking_details ADD CONSTRAINT FK_BOOKING_DETAILS_ON_BOOKINGENTITY FOREIGN KEY (booking_entity_id) REFERENCES booking (id);
I would highly appreciate any inputs regarding this. Thank you.
I tried using the "extend" method on my BookingDetails entity to BookingEntity. This run my java springboot application but for some reason I can't fetch data with internal error 500 in postman. So I change my sql commands with the one-to-one relationship mapping but I got the above errors.
Just out of interest - how you're planning to insert new entries given the schema? In order to create booking you'd need to have booking_details created and vice versa.
The error message indicates that the table "BOOKING_DETAILS" is not found when you're trying to create a foreign key constraint in the "booking" table.
You need to make sure that the "booking_details" table is created before creating the foreign key constraint in the "booking" table. You can do this by reordering your migration script to create the "booking_details" table before creating the "booking" table with the foreign key constraint.
Additionally, check that the table name and column name used in the foreign key constraint statement are correct and match the names used in the "booking_details" table.
Solution: put this command on the last part of the sql so that the two tables must be created first before it can be altered.
"ALTER TABLE booking ADD CONSTRAINT FK_BOOKING_ON_BOOKING_DETAILS FOREIGN KEY (booking_details_id) REFERENCES booking_details (booking_entity_id);"
I am working on a project with Java, Spring Boot, JPA and H2 database.
However, I am confused with how the database tables have been designed.
There are 3 tables A,B and C.
Table A has Table B's primary key as foreign key.
Table B has Table C's primary key as foreign key.
Table C has Table A's primary key as foreign key.
Since each table is dependent on other tables, when I am creating the schema of all the three I am getting an error indicating Table B is not found
I have even tried using ALTER commands but still facing the same issue.
Here is my code
DROP TABLE IF EXISTS TEAMS;
CREATE TABLE IF NOT EXISTS TEAMS (
`team_id` int (11) NOT NULL AUTO_INCREMENT,
`name` varchar (100) NOT NULL DEFAULT '0',
`train_id` int (11) NOT NULL DEFAULT '0',
PRIMARY KEY (`team_id`),
CONSTRAINT `FK_teams_trains` FOREIGN KEY (`train_id`) REFERENCES TRAINS (`train_id`)
);
DROP TABLE IF EXISTS USERS;
CREATE TABLE IF NOT EXISTS USERS (
`user_id` int (11) NOT NULL AUTO_INCREMENT,
`team_id` int (11) DEFAULT NULL,
`reports_to` int (11) DEFAULT NULL,
PRIMARY KEY (`user_id`),
CONSTRAINT `FK_users_teams` FOREIGN KEY (`team_id`) REFERENCES TEAMS (`team_id`),
CONSTRAINT `FK_users_users` FOREIGN KEY (`reports_to`) REFERENCES USERS (`user_id`)
);
DROP TABLE IF EXISTS TRAINS;
CREATE TABLE IF NOT EXISTS TRAINS` (
train_id INT (11) NOT NULL AUTO_INCREMENT,
train_name varchar (100) NOT NULL DEFAULT '0',
team_coach INT (11) NOT NULL DEFAULT '0',
train_vp INT (11) NOT NULL DEFAULT '0',
PRIMARY KEY (`train_id`)
);
ALTER TABLE TRAINS ADD CONSTRAINT `FK_trains_users` FOREIGN KEY (`team_coach`) REFERENCES USERS (`user_id`);
ALTER TABLE TRAINS ADD CONSTRAINT `FK_trains_users_2` FOREIGN KEY (`train_vp`) REFERENCES USERS (`user_id`);
ALTER TABLE TEAMS ADD CONSTRAINT `FK_teams_trains` FOREIGN KEY (`train_id`) REFERENCES TRAINS (`train_id`);
ALTER TABLE USERS ADD CONSTRAINT `FK_users_teams` FOREIGN KEY (`team_id`) REFERENCES TEAMS (`team_id`);
ALTER TABLE USERS ADD CONSTRAINT `FK_users_users` FOREIGN KEY (`reports_to`) REFERENCES USERS (`user_id`);
How can I solve this issue?
Created two tables namely Address and Employee.With relationship employee has a n address. The DB script as below.
create table address(addressid int,city varchar(10),pincode varchar(10));
insert into address(addressid,city,pincode) values(201,'Hosur',635109);
create table employee(empid int , firstname varchar(20),lastname varchar(20),department varchar(10),emailAddress varchar(50),baseLocation varchar(20),address int,FOREIGN KEY (Address) REFERENCES Address(addressId));
But I get the following error while trying to create the employee table:
Error Code: 1822. Failed to add the foreign key constraint. Missing
index for constraint 'employee_ibfk_1' in the referenced table
'Address' 0.117 sec
You should probably add a primary key on addressid in the Address table, this will create the index needed. In your current script there is no guarantee that addressid will be unique, hence if there would be duplicates a foreign key could never determine which row to refer to.
create table address(addressId int primary key not null, city varchar(10), pincode varchar(10));
because foreign key references primary key.
you don't have primary key in table address.
like this,
create table address(addressid int primary key,city varchar(10),pincode varchar(10));
create table employee(empid int , firstname varchar(20),lastname varchar(20),department varchar(10),emailAddress varchar(50),baseLocation varchar(20),address int ,FOREIGN KEY (address) REFERENCES address(addressid));
insert into address(addressid,city,pincode) values(201,'Hosur',635109);
You need to add the primary key constraint in the address table, inorder to add foreign key references in employee table
try with the following code:
create table address(addressid int primary key not null,city varchar(10),pincode varchar(10));
insert into address(addressid,city,pincode) values(201,'Hosur',635109);
create table employee(empid int , firstname varchar(20),lastname varchar(20),department varchar(10),emailAddress varchar(50),baseLocation varchar(20),address int,FOREIGN KEY (address) REFERENCES address(addressid));
Table Name:
CUSTOMER_INFORMATION
Customer_ID (PK)
Customer_Name
Mobile_Number
EVENT_INFORMATION
Event_ID (PK)
Event_Name
RELATION_TABLE
Event_ID (FK)
Customer_ID (FK)
First You will have to add records in CUSTOMER_INFORMATION, EVENT_INFORMATION tables
Insert into CUSTOMER_INFORMATION table
INSERT INTO CUSTOMER_INFORMATION VALUES (123,'new user','+923417874563');
Insert into EVENT_INFORMATION table
INSERT INTO EVENT_INFORMATION VALUES (456,'new event');
Now we can add new record in the RELATION_TABLE by using above primary keys
INSERT INTO RELATION_TABLE VALUES (456,123);
But there must be some information in the RELATION_ABLE that escribes the relation. and primary key of the relation table
I have below tables:
create table TABLE1 ( id int(10) unsigned NOT NULL AUTO_INCREMENT, deptId int(11) NOT NULL, DeptName varchar(32) NOT NULL, PRIMARY KEY (id), KEY Dept (deptId, DeptName))
create table TABLE2 ( id int(10) unsigned NOT NULL AUTO_INCREMENT, empId int(11) NOT NULL, DeptName varchar(32) NOT NULL, PRIMARY KEY (id), KEY DeptName (DeptName), CONSTRAINT T2FK FOREIGN KEY (DeptName) REFERENCES TABLE1 (DeptName))
TABLE1 has a MUL key defined with both dept id and dept name.
TABLE2 has a Foreign key which references only Dept name from TABLE1
The DTO for TABLE2 gets created like below:
#org.hibernate.annotations.NotFound(action = org.hibernate.annotations.NotFoundAction.IGNORE)
#javax.persistence.ManyToOne(targetEntity = org.amru.persistence.dto.TABLE1DTOImpl.class, fetch=javax.persistence.FetchType.EAGER)
#javax.persistence.JoinColumn(name = "deptName")
public org.amru.persistence.dto.TABLE1DTO getTABLE1() {
return TABLE1;
}
When I try to insert a row in TABLE2, it fails with foreign key constraint violation exception.
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`amru`.`TABLE2`, CONSTRAINT `T2FK` FOREIGN KEY (`DeptName`) REFERENCES `TABLE1` (`DeptName`))
I also see a EntityExistsException when I debug
What is possibly wrong? Is it recommended to refer a part of MUL key as foreign key in another table?
I am using jpa, hibernate, jboss, ejb and mysql
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Cannot add or update a child row: a foreign key constraint fails
What is possibly wrong?
This is very clear that, DeptName is foreign key in TABLE2, which is referring from TABLE1. So, you are not allowed to change the value in parent table as the data is being referenced in other table.
If you are supposed to do this, then you need to alter your table to apply cascade changes to child table as well for your Foreign Key
FOREIGN KEY (DeptName) REFERENCES TABLE1 (DeptName) ON DELETE CASCADE ON UPDATE CASCADE