MYSQL in PHPMYADMIN - create table relationship from one table - mysql

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

Related

Unable to create foreign key on mysql

Hi i'm trying to create a simple MySQL database. I write the following script
CREATE TABLE office (
num_office varchar(10) NOT NULL,
name varchar(45),
address varchar(45),
numder varchar(4),
city varchar(45)
);
CREATE TABLE office_phone(
n_office varchar(10) NOT NULL,
phone varchar(15) NOT NULL,
PRIMARY KEY(n_office,phone),
FOREIGN KEY (n_office) REFERENCES office(num_office)
ON DELETE RESTRICT
ON UPDATE CASCADE
);
but Error Code 1822 is appeared.
How can i fix it?
thank you in andvance
Foreign keys can reference only columns that are primary keys or at least have an index on them (thanks #Uueerdo). For example:
ALTER TABLE OFFICE ADD CONSTRAINT offnum_unq UNIQUE (NUM_OFFICE);
This forces the referenced column to have unique values and also creates an index on it. Or you could also do:
CREATE INDEX offnum_idx ON OFFICE(NUM_OFFICE);
Now your second CREATE should work.
Reference column (Column you referenced as foreign key) should have the index added to it. You can add Index to the column "num_office" in "office" table and try creating the "office_phone" table. Refer the following queries
Create Table "office" with the index added to "num_office"
CREATE TABLE office (
num_office varchar(10) NOT NULL,
name varchar(45),
address varchar(45),
numder varchar(4),
city varchar(45),
INDEX num_office_idx (num_office)
);
OR you can add index after creating the "office" table using
ALTER TABLE office Add Index num_office_indx (num_office);
This will let you to create the table "office_phone" successfully with the reference key pointing to "num_office" column of "office" table.
CREATE TABLE office_phone(
n_office varchar(10) NOT NULL,
phone varchar(15) NOT NULL,
PRIMARY KEY(n_office,phone),
FOREIGN KEY (n_office) REFERENCES office(num_office)
ON DELETE RESTRICT
ON UPDATE CASCADE
);
Refer this page for more details

Transferring from sql developer to mysql

So i have a few tables in my database in Sql developer which I still have the queries from. If I try to put it in mysql it comes out with some errors so i'm wondering what is different and why is it not working like what would I need to change.
These are some of the tables I created in sql which i'm trying to create now in mysql:
create table EspecialidadesMedicas(
IdEspecialidad number(4) constraint pk_EspecialidadesMedicas primary key,
DescripcionEspecialidad varchar2(30));
create table Doctores(
IdDoctor number(5) constraint pk_Doctores primary key,
NombreDoctor varchar2(30),
Salario number(12,2),
Especialidad constraint fk1_Doctores references EspecialidadesMedicas);
create table Consultorios(
IdConsultorio number(4) constraint pk_Consultorios primary key,
Tamano varchar2(30),
Construido date);
Your first statement will become this:
create table EspecialidadesMedicas(
IdEspecialidad int primary key,
DescripcionEspecialidad varchar(30)
);
Your second statement is likely to become this:
create table Doctores(
IdDoctor int primary key,
NombreDoctor varchar(30),
Salario decimal(12,2),
Especialidad int,
constraint fk1_Doctores foreign key (Especialidad) references EspecialidadesMedicas (IdEspecialidad)
);
Your third statement will turn out to be:
create table Consultorios(
IdConsultorio int primary key,
Tamano varchar(30),
Construido date
);
Try this out in MySQL.
Your first table would look like this in MySQL:
CREATE TABLE `de`.`EspecialidadesMedicas` (
`IdEspecialidad` INT NOT NULL AUTO_INCREMENT,
`DescripcionEspecialidad` VARCHAR(30) NULL,
PRIMARY KEY (`IdEspecialidad`));
As you see, there are quite some differences in syntax, data types and features which can not all be covered here. (e.g. AUTO INCREMENT)
The easiest way to get into this is to use a toollike MySQL Workbench. It allows you to use a GUI to create your tables and displays the executed SQL. This way you see the differences.
I also suggest to read some migration tutorials like these:
https://blog.toadworld.com/2017/03/17/migrating-from-oracle-to-mysql
http://www.sqlines.com/oracle-to-mysql

MySQL Error Code: 1824. Failed to open the referenced table

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.

Failed to open the referenced table

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

mysql table is not creating

I am getting error when I create table with foreign key
create table _users(_id int(20) unsigned NOT NULL AUTO_INCREMENT,
_user_fullname varchar(50)not null,
_user_username varchar(160) not null,
_user_password varchar(200) not null,_user_remember_me tinyint,
_user_email varchar(30),
_user_mobile varchar(15),
_user_age varchar(10)
,primary key(_id,_user_email,_user_mobile));
_users table created successfully..there were no error..
But When I want to create employee table :
CREATE TABLE employee ( _Id INT NOT NULL AUTO_INCREMENT,
_user_mobile VARCHAR(15) not null,
_name varchar(15),
_org varchar(10),
PRIMARY KEY (_Id),
foreign key (_user_mobile) references _users(_user_mobile));
Its showing error:
ERROR 1005 (HY000): Can't create table 'DB.employee' (errno: 150)
What am I doing wrong??
Hey In this case you just need to do one thing ,
you just need to add index to the reference column of the user table and then run the create table for employee
ALTER TABLE `_users` ADD INDEX (`_user_mobile`);
After running above query just run the below query :-
CREATE TABLE `employee`(
`_Id` INT(11) NOT NULL AUTO_INCREMENT,
`_user_mobile` VARCHAR(15) NOT NULL,
`_name` VARCHAR(15),
`_org` VARCHAR(10),
PRIMARY KEY (`_Id`),
FOREIGN KEY (`_user_mobile`) REFERENCES `_users`(`_user_mobile`) );
In this way you will get rid of the error 1005 of mysql which says that you need to have index on the reference column of parent table.
150 is a foreign key error:
C:\>perror 150
MySQL error code 150: Foreign key constraint is incorrectly formed
Getting the exact error message is very tricky. You need to run this query:
show engine innodb status
... and search in the output:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
160627 14:09:32 Error in foreign key constraint of table test/employee:
foreign key (_user_mobile) references _users(_user_mobile)):
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.
See http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
Once you know that, it'd be easy to add the missing index:
ALTER TABLE `_users`
ADD UNIQUE INDEX `_user_email` (`_user_email`);
But I wouldn't if I were you. It's weird to use mobile phone number as key. Instead, just simplify the primary key:
create table _users(_id int(20) unsigned NOT NULL AUTO_INCREMENT,
_user_fullname varchar(50)not null,
_user_username varchar(160) not null,
_user_password varchar(200) not null,_user_remember_me tinyint,
_user_email varchar(30),
_user_mobile varchar(15),
_user_age varchar(10)
,primary key(_id));
... and use in the linked table:
CREATE TABLE employee ( _Id INT NOT NULL AUTO_INCREMENT,
_user_id int(20) unsigned not null,
_name varchar(15),
_org varchar(10),
PRIMARY KEY (_Id),
foreign key (_user_id) references _users(_id));
The problem is in the foreign key part. If you remove that, table will be created without a problem.
If you need to use that foreign key, you need to use InnoDB as the storage engine of MySQL. InnoDB allows a foreign key constraint to reference a non-unique key as can be seen in here.