When I try to create the 'Project table I get this error Code: 1824. Failed to open the referenced table 'Employee'.
My syntax:
CREATE DATABASE IF NOT EXISTS Test;
USE Test;
CREATE TABLE IF NOT EXISTS Customer (
CustomerID VARCHAR(7) NOT NULL,
CustomerName VARCHAR(50),
CustAdress VARCHAR(70),
CustEmail VARCHAR(50),
PRIMARY KEY (CustomerID)
);
CREATE TABLE IF NOT EXISTS Employee (
EmpID VARCHAR(7) NOT NULL,
EmpName VARCHAR(50),
Position VARCHAR(30),
EmpTimePrice INT(4),
PRIMARY KEY (EmpID)
);
CREATE TABLE IF NOT EXISTS Project (
ProjectNo VARCHAR(7),
ProjectName VARCHAR(50),
StartDate DATE,
ProjTimePrice INT(6),
CustomerID VARCHAR(7),
EmpID VARCHAR(7),
PRIMARY KEY (ProjectNo),
FOREIGN KEY (EmpID) REFERENCES Employee (EmpID),
FOREIGN KEY (CustomerID) REFERENCES Customer (CustomerID)
);
CREATE TABLE IF NOT EXISTS ProjectWork (
ProjectNo VARCHAR(7),
EmpID VARCHAR(7),
PWDATE DATE,
HoursWorked INT(5),
FOREIGN KEY (ProjectNo) REFERENCES Project (ProjectNo),
FOREIGN KEY (EmpID) REFERENCES Employee (EmpID)
);
The names look correct to me and I have referenced the foreign key so I don't understand why I get this error. Any help would be appreciated, thanks.
This normally happens when the two tables have different Table engines. so check both tables if they have same table engines. for example MYISAM do not support Foreign Keys
Just edited EmpID to empID and it worked for some reason.
One of the easiest ways to get this error is referencing a table that doesn't exist yet. Eg if you run the following code on a new schema:
create table ttest (bob varchar(10) not null,
constraint fkbob foreign key (bob) references other(bob) );
... you will get the MySQL error:
Error Code: 1824. Failed to open the referenced table 'other'
Because the other table doesn't exist.
The code in the question above creates Employee before referencing it. However, note that the CREATE DATABASE and CREATE TABLE statements have IF EXISTS, but there are no DROP IF EXISTS statements, as when creating a new database. If you were debugging a table creation script, changing and fixing things as you go, it would have been pretty easy to get into an inconsistent state where the tables were out of synch with the code. This would also explain why other people could run the code cleanly, because these tables didn't exist in their schema yet.
Related
I am new with SQL and I am not entirely sure why I am getting the error: ERROR 1824 (HY000) at line 5: Failed to open the referenced table 'products'
Operation failed with exitcode 1
Here is my code
drop database if exists cc;
create database cc /*!40100 default character set utf8 */;
use cc;
create table Customers(
CustomerID int not null,
FirstName varchar(255),
LastName varchar(255),
address varchar(255),
phoneNO varchar(11),
prodID int,
quantity int,
primary key (CustomerID),
foreign key (prodID) references Products(itemID)
);
create table Employees(
EmployeeID int not null,
FirstName varchar(255),
LastName varchar(255),
address varchar(255),
phoneNO varchar(11),
ManagerID int not null,
primary key (EmployeeID),
foreign key (managerID) references Managers(mgrID)
);
create table Managers(
mgrID int not null,
salary float,
MaxSupervisingCapacity int,
foreign key (mgrID) references Employees(EmployeeID),
primary key (mgrID)
);
You can't create a foreign key that references another table until after you create that other table. In the Customers table you have
foreign key (prodID) references Products(itemID)
but there's no Products table yet. And in Employees you have
foreign key (managerID) references Managers(mgrID)
but the Managers table is created after it.
You need to reorder your table creations. Create Products before Customers.
Also, you can't have circular foreign key relationships. Employees.managerID references Managers and Managers.mgrID references Employees. This creates a chicken-and-egg problem: how would you create the first employee, since it needs a manager, but you can't create the first manager because it needs to refer to an employee.
You can solve this problem by allowing the foreign keys to be null. So you create the first employee with a null manager, then create the manager, then replace the managerID with this ID.
There's also a chicken-and-egg problem when creating these two tables. You can't reference a table that has yet to be created. So leave out the foreign key specification when creating the table, and add it later with ALTER TABLE.
create table Employees(
EmployeeID int not null,
FirstName varchar(255),
LastName varchar(255),
address varchar(255),
phoneNO varchar(11),
ManagerID int not null,
primary key (EmployeeID)
);
create table Managers(
mgrID int not null,
salary float,
MaxSupervisingCapacity int,
foreign key (mgrID) references Employees(EmployeeID),
primary key (mgrID)
);
alter table Employees add foreign key (managerID) references Managers(mgrID);
You can just surround the whole thing with a
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS;
SET FOREIGN_KEY_CHECKS=0;
## all of your schema and inserts
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
This change of the check will cause the engine not to do checks on those keys and just add them as is.
I have Just fixed this problem by Cheking both tables Storage Engine same and by settings the same Attributes for reff tables column.
you can try assigning the "ENGINE = INNODB" of the tables when creating them. One of the drawbacks when creating Foreign keys is that, the foreign keys can only be defined for certain storage engines (like InnoDB). The server accepts foreign key definitions for other storage engines but silently ignores them.
Example:
CREATE TABLE `Customers` (
CustomerID int not null,
FirstName varchar(255),
...
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
As you can see, when the table is finished, it is assigned the Engine = InnoDB and the default charset.
If you want to alter the table, you can do the following:
ALTER TABLE `Customers` ENGINE = InnoDB ;
If it served you, do not forget to approve the answer, you can make life easier for many developers.
I tried everything and nothing didn´t really work for me until I did the most simple thing. Go to SCHEMAS select the one that has de databases you are trying to work with and with right click, select set as default schema. That´s all, it worked perfectly.
Hope it helps
This is what I have tried:
create table books(bcode int(5) primary key, bname varchar(45));
and
create table customers(cid int(4), cname varchar(20), cadd varchar(40), bcode,
varchar(45), foreign key(bcode) references books(bcode));
After executing the second statement, the following error shows up:
ERROR 1215 (HY000): Cannot add foreign key constraint
I'm having trouble coming up with a solution. Any help is appreciated.
In the first table books you use bcode as integer
But in the second table you use bcode as varchar,
So, right one is
create table customers(cid int(4), cname varchar(20), cadd varchar(40), bcode
int(5), foreign key(bcode) references books(bcode));
The current tables I have are as follows:
CREATE TABLE course(
CourseNum INT(11),
CourseName VARCHAR(30),
NumOfUnit INT(11),
PRIMARY KEY(CourseNum)
);
CREATE TABLE timeandloc(
CourseNum INT(11),
Quarter VARCHAR(20),
DayTime VARCHAR(40),
RoomNum INT,
PRIMARY KEY(CourseNum, Quarter, DayTime),
FOREIGN KEY(CourseNum) REFERENCES course (CourseNum)
);
I was able to add those fine using a query, but when I try to add this table:
CREATE TABLE student(
StudentName VARCHAR(30),
CourseNum INT(11),
Quarter VARCHAR(20),
PRIMARY KEY(StudentName, CourseNum, Quarter),
FOREIGN KEY(CourseNum) REFERENCES course(CourseNum),
FOREIGN KEY(Quarter) REFERENCES timeandloc(Quarter)
);
I get
Error code: 1215. Cannot add foreign key constraint.
It seems to be this line that's the culprit:
FOREIGN KEY(Quarter) REFERENCES timeandloc(Quarter)
When I try to add the table without that line, everything works fine without a hitch.
I'm very new to MySQL and databases in general so I'm not sure what's wrong. Any help would be great. Thanks.
create a separate index on Quarter field in timeandloc table and then create problematic create table query.
alter table timeandloc add index idx_Quarter(Quarter);
CREATE TABLE student(
StudentName VARCHAR(30),
CourseNum INT(11),
Quarter VARCHAR(20),
PRIMARY KEY(StudentName, CourseNum, Quarter),
FOREIGN KEY(CourseNum) REFERENCES course(CourseNum),
FOREIGN KEY(Quarter) REFERENCES timeandloc(Quarter)
);
Update:
For performance point of view joining field in both tables (parent/child) should be indexed. When we create foreign key then mysql itself create an index on the field we create foreign key but could not allow without index on referenced column in referenced table. As index works from left to right, so in your case index for Quarter column will not be used from primary key, so need to create a separate index on it.
I'm trying to start using Liquibase for a project that already has multiple SQL changelog files (that were previously maintained by hand). Using an advise from somewhere on stackoverflow I added a
<includeAll path="db/initial"/>
directive to my initial change log file, but it was failing with a not very useful
You have an error in your SQL syntax
message. Playing around I figured out that the problem is with multiple sql statements in the file. As long as I supplied a file with only one statement it worked.
So how do I tell Liquibase to execute multiple statements from an sql file?
A bit more searching to figure out that the problem is not with Liquibase but with MySql driver that by default refuses to execute multiple statements.
The key bit was to add allowMultiQueries=true to my connection string:
url: jdbc:mysql://localhost/test_project?allowMultiQueries=true
I would expected that you'd be using a sql_file refactoring to import a SQL file. It supports a "splitStatements" attribute that would solve your issue without the need to make changes to your JDBC settings.
The include statement is normally used to import liquibase changelogs.... Have you adapted your files to be formatted SQL changelogs? It would be well worth trying this out, I've included an example file:
Example
scottTiger.sql
--liquibase formatted sql
--changeset mark:1
CREATE TABLE BONUS (ENAME VARCHAR(10) NOT NULL, JOB VARCHAR(9) NOT NULL, SAL DECIMAL(7, 2), COMM DECIMAL(7, 2));
ALTER TABLE BONUS ADD CONSTRAINT BONUS_PK PRIMARY KEY (ENAME, JOB);
--rollback DROP TABLE BONUS;
--changeset mark:2
CREATE TABLE DEPARTMENT (DEPTNO INT NOT NULL, NAME VARCHAR(14), LOCATION VARCHAR(13), CONSTRAINT DEPT_PK PRIMARY KEY (DEPTNO));
--rollback DROP TABLE DEPARTMENT;
--changeset mark:3
CREATE TABLE EMPLOYEE (EMPNO INT NOT NULL, NAME VARCHAR(10), JOB VARCHAR(9), BOSS INT, HIREDATE VARCHAR(12), SALARY DECIMAL(7, 2), COMM DECIMAL(7, 2), DEPTNO INT, CONSTRAINT EMP_PK PRIMARY KEY (EMPNO));
ALTER TABLE PUBLIC.EMPLOYEE ADD CONSTRAINT BOSS_FK FOREIGN KEY (BOSS) REFERENCES PUBLIC.EMPLOYEE (EMPNO) ON UPDATE RESTRICT ON DELETE RESTRICT;
ALTER TABLE PUBLIC.EMPLOYEE ADD CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPTNO) REFERENCES PUBLIC.DEPARTMENT (DEPTNO) ON UPDATE RESTRICT ON DELETE RESTRICT;
--rollback DROP TABLE EMPLOYEE;
--changeset mark:4
CREATE TABLE PROJECT (PROJECTNO INT NOT NULL, DESCRIPTION VARCHAR(100), START_DATE VARCHAR(12), END_DATE VARCHAR(12), CONSTRAINT PROJECT_PK PRIMARY KEY (PROJECTNO));
--rollback DROP TABLE PROJECT;
--changeset mark:5
CREATE TABLE ROLE (ROLE_ID INT NOT NULL, DESCRIPTION VARCHAR(100), CONSTRAINT ROLE_PK PRIMARY KEY (ROLE_ID));
--rollback DROP TABLE ROLE;
--changeset mark:6
CREATE TABLE PROJECT_PARTICIPATION (PROJECTNO INT NOT NULL, EMPNO INT NOT NULL, START_DATE VARCHAR(12) NOT NULL, END_DATE VARCHAR(12), ROLE_ID INT);
ALTER TABLE PROJECT_PARTICIPATION ADD CONSTRAINT PARTICIPATION_PK PRIMARY KEY (PROJECTNO, EMPNO, START_DATE);
ALTER TABLE PUBLIC.PROJECT_PARTICIPATION ADD CONSTRAINT EMPLOYEE_FK FOREIGN KEY (EMPNO) REFERENCES PUBLIC.EMPLOYEE (EMPNO) ON UPDATE RESTRICT ON DELETE RESTRICT;
ALTER TABLE PUBLIC.PROJECT_PARTICIPATION ADD CONSTRAINT PROJECT_FK FOREIGN KEY (PROJECTNO) REFERENCES PUBLIC.PROJECT (PROJECTNO) ON UPDATE RESTRICT ON DELETE RESTRICT;
ALTER TABLE PUBLIC.PROJECT_PARTICIPATION ADD CONSTRAINT ROLE_FK FOREIGN KEY (ROLE_ID) REFERENCES PUBLIC.ROLE (ROLE_ID) ON UPDATE RESTRICT ON DELETE RESTRICT;
--rollback DROP TABLE PROJECT_PARTICIPATION;
--changeset mark:7
CREATE TABLE SALARYGRADE (GRADE INT NOT NULL, LOSAL INT NOT NULL, HISAL INT NOT NULL, CONSTRAINT SALGRADE_PK PRIMARY KEY (GRADE));
--rollback DROP TABLE SALARYGRADE;
Note:
One thing I love about liquibase is its support for rollbacks.
I want to create a table relationship with MYSQL PHPMYADMIN.
I have this Create table:
CREATE TABLE students(code_students int(8)not null AUTO_INCREMENT,
name_students varchar(25),
age_students int(3),
degree_program varchar(25),
code_advisor int(8)not null,
primary key(code_students, code_advisor)
);
and i want to make a create table named advise relationship between code_students, code_advisor.
Ok this is my tryout.
CREATE TABLE advise (
code_students int(8),
code_advisor int(8),
primary key(code_students, code_advisor),
foreign key(code_students)references students(code_students),
foreign key(code_advisor)references students(code_advisor)
);
mySQL says :
A FOREIGN KEY constraint that references a non-UNIQUE key is not standard SQL. It is an InnoDB extension to standard SQL
Try adding the UNIQUE keyword to your first table:
CREATE TABLE students(
code_students int(8)not null unique AUTO_INCREMENT,
name_students varchar(25),
age_students int(3),
degree_program varchar(25),
code_advisor int(8)not null unique,
primary key(code_students, code_advisor)
);
Check out this sqlFiddle and see how it works, then try removing the UNIQUE keywords and see that you get the same error that you mentioned. ( Hit the Build Schema button )
http://sqlfiddle.com/#!2/46b69