mysql error 1215 cannot add foreign key contraint - mysql

DROP TABLE IF EXISTS desk;
DROP TABLE IF EXISTS user;
DROP TABLE IF EXISTS authority;
CREATE TABLE authority
(
authorityId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
deskId INT DEFAULT 0,
authorityName VARCHAR(50) NOT NULL,
descriptions VARCHAR(100) NOT NULL,
userLevel TINYINT NOT NULL,
actions VARCHAR(300) DEFAULT NULL,
setDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE desk
(
deskId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
deskName CHAR(50) NOT NULL,
deskLink VARCHAR(100) NOT NULL,
details VARCHAR(350) DEFAULT NULL,
setDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
closeDate TIMESTAMP DEFAULT NULL,
userId INT DEFAULT NULL,
status TINYINT(1) DEFAULT 0
);
CREATE TABLE user
(
userId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
userName CHAR(150) NOT NULL,
password VARCHAR(500) NOT NULL,
department VARCHAR(150) DEFAULT NULL,
deskId INT NOT NULL,
status TINYINT(1) DEFAULT NULL,
userLevel TINYINT NOT NULL,
FOREIGN KEY (deskId) REFERENCES desk (deskId) ON DELETE CASCADE,
FOREIGN KEY (userLevel) REFERENCES authority (userLevel)
);
Error while executing query.
Error Code: 1215 .Cannot add foreign key contraint
I have tried many way but still cannot solve the problem, i tried change userLevel type to INT both table user and authority but nothing went to better
I really not know how to fix this problem, please help

Follow below steps
1) You must change your second query to
DROP TABLE IF EXISTS desk;
CREATE TABLE desk
(
deskId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
deskName CHAR(50) NOT NULL,
deskLink VARCHAR(100) NOT NULL,
details VARCHAR(350) DEFAULT NULL,
setDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
closeDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
userId INT DEFAULT NULL,
status TINYINT(1) DEFAULT 0
);
2) As your column authority.userLevel is not a primary key and you want to use it as foreign key in other table you need to create index on authority.userLevel column
use below query
ALTER TABLE `authority` ADD INDEX `UserLevelIndex` (`userLevel`);
3) Run your third query as it is to create user table

Run Following queries
DROP TABLE IF EXISTS desk;
DROP TABLE IF EXISTS user;
DROP TABLE IF EXISTS authority;
CREATE TABLE authority
(
authorityId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
deskId INT DEFAULT 0,
authorityName VARCHAR(50) NOT NULL,
descriptions VARCHAR(100) NOT NULL,
userLevel TINYINT NOT NULL,
actions VARCHAR(300) DEFAULT NULL,
setDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
index `cr_index` (userLevel)
);
CREATE TABLE desk
(
deskId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
deskName CHAR(50) NOT NULL,
deskLink VARCHAR(100) NOT NULL,
details VARCHAR(350) DEFAULT NULL,
setDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
closeDate TIMESTAMP DEFAULT '0000-00-00 00:00:00',
userId INT DEFAULT NULL,
status TINYINT(1) DEFAULT 0
);
CREATE TABLE `user`
(
userId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
userName CHAR(150) NOT NULL,
password VARCHAR(500) NOT NULL,
department VARCHAR(150) DEFAULT NULL,
deskId INT NOT NULL,
status TINYINT(1) DEFAULT NULL,
userLevel TINYINT NOT NULL,
FOREIGN KEY (deskId) REFERENCES desk (deskId) ON DELETE CASCADE,
FOREIGN KEY (userLevel) REFERENCES authority (userLevel)
);
In your query you write timestamp default value NULL and you can create a non index key userLevel as a foreign key so from your query remove default value or change the default value 0000-00-00 00:00:00(in desk table) and add index in userLevel column (in authority table)
I hope this will work for you

Related

Create a relationship between the tables when the table is first created

I use mysql
in my database
I want to create multiple tables with delete and update relationship
as an example
I want to link the profiles table to the users table
Associate the mm_id_user column from the users table with the mm_id_profile column from the profiles table
What I actually tried to do is this example and it didn't work for me
https://stackoverflow.com/a/260453/10206991
https://stackoverflow.com/a/9796950/10206991
The code used to create the users table and it succeeds in creating the table
CREATE TABLE users (
mm_email VARCHAR(255) NOT NULL,
mm_id_user int NOT NULL AUTO_INCREMENT,
mm_name VARCHAR(25) NOT NULL,
mm_password VARCHAR(255) NOT NULL,
mm_code_reset_pass VARCHAR(100) NOT NULL,
mm_code_check_email VARCHAR(100) NOT NULL,
mm_status CHAR(1) NOT NULL DEFAULT '0',
mm_date_create_account TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
mm_date_last_login TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
mm_is_login CHAR(1) NOT NULL DEFAULT '0',
PRIMARY KEY (mm_id_user, mm_email)
)ENGINE=InnoDB DEFAULT CHARSET=utf8 DEFAULT COLLATE utf8_unicode_ci;
The code used to create the profiles table. He failed to create the table
CREATE TABLE profiles (
mm_id_profile VARCHAR(255) NOT NULL,
mm_image_user TEXT NOT NULL,
mm_num_stores_all VARCHAR(4) NOT NULL,
mm_num_stores_exist VARCHAR(4) NOT NULL,
mm_name_public VARCHAR(25) NOT NULL,
mm_email_public VARCHAR(255) NOT NULL,
mm_phone_public VARCHAR(20) NOT NULL,
mm_location_public TEXT NOT NULL,
mm_update_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX index_profiles(mm_name_public, mm_email_public),
PRIMARY KEY (mm_id_profile),
FOREIGN KEY (mm_id_profile) REFERENCES users(mm_email) ON DELETE CASCADE
)ENGINE=InnoDB DEFAULT CHARSET=utf8 DEFAULT COLLATE utf8_unicode_ci;
But if you remove the following line from the profiles table, it will be created
But there is definitely no relationship between the two tables
FOREIGN KEY (mm_id_profile) REFERENCES users(mm_email) ON DELETE CASCADE
This is the error message that appears when creating a profiles table
#1005 - Can't create table `mustforu_test`.`profiles` (errno: 150 "Foreign key constraint is incorrectly formed") (Details…)
There's no reason to put both mm_id_user and mm_email in the primary key of users. If you want emails to be unique, it should have its own unique index. Your current primary key would allow duplicate emails with different IDs.
CREATE TABLE users (
mm_email VARCHAR(255) NOT NULL,
mm_id_user int NOT NULL AUTO_INCREMENT,
mm_name VARCHAR(25) NOT NULL,
mm_password VARCHAR(255) NOT NULL,
mm_code_reset_pass VARCHAR(100) NOT NULL,
mm_code_check_email VARCHAR(100) NOT NULL,
mm_status CHAR(1) NOT NULL DEFAULT '0',
mm_date_create_account TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
mm_date_last_login TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
mm_is_login CHAR(1) NOT NULL DEFAULT '0',
PRIMARY KEY (mm_id_user),
UNIQUE KEY (mm_email)
)ENGINE=InnoDB DEFAULT CHARSET=utf8 DEFAULT COLLATE utf8_unicode_ci;
Giving mm_email its own index will allow the foreign key in profiles to work.

Create two tables customer_data and order_data in SQL in a single execution via PHP

CREATE TABLE IF NOT EXISTS customers_data (
id int(20) UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL,
INVOICE_ID varchar(50) NOT NULL,
_NAME varchar(255) NOT NULL,
MOBILE bigint(12) NOT NULL,
GSTIN varchar(20) NOT NULL,
_ADDRESS varchar(255) NOT NULL,
EMAIL varchar(255) NOT NULL,
_STATE varchar(50) NOT NULL,
MODE varchar(10) NOT NULL,
_DATE date NOT NULL DEFAULT current_timestamp(),
total_qty int(11) NOT NULL,
total_amount decimal(40,2) NOT NULL,
total_sc_gst decimal(30,2) NOT NULL,
Round_Off float(2,2) NOT NULL,
grand_total decimal(50,0) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
customer_data created sucessfully.
But there is an error in order_data regarding foreign key. Remember I want to create these two table in a same time.
CREATE TABLE IF NOT EXISTS order_data (
id int(20) UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL,
cus_id int(20) NOT NULL,
ITEM varchar(255) NOT NULL,
HSN varchar(50) NOT NULL,
QTY int(15) NOT NULL,
RATE decimal(40,2) NOT NULL,
S_C_GST decimal(30,2) NOT NULL,
TOTAL decimal(50,2) NOT NULL,
_DATE timestamp NOT NULL DEFAULT current_timestamp(),
FOREIGN KEY(cus_id) REFERENCES customers_data(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
I got this error.
#1005 - Can't create table test. (errno: 150 "Foreign
key constraint is incorrectly formed")
I think you are using MySQL. You have not used Constraint with Foreign Key. Try the below query.
CREATE TABLE IF NOT EXISTS order_data (
id int(20) UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL,
cus_id int(20) NOT NULL,
ITEM varchar(255) NOT NULL,
HSN varchar(50) NOT NULL,
QTY int(15) NOT NULL,
RATE decimal(40,2) NOT NULL,
S_C_GST decimal(30,2) NOT NULL,
TOTAL decimal(50,2) NOT NULL,
_DATE timestamp NOT NULL DEFAULT current_timestamp(),
**CONSTRAINT <FK_NAME>** FOREIGN KEY(cus_id) REFERENCES customers_data(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Making the table "at the same time" is not the problem you need to solve, (it's not possible anyway).
You can't make a foreign key if the data type is different from the data type of the referenced column.
order_data.cus_id is an INT column.
customers_data.id is an INT UNSIGNED column.
Change either one or the other data type, so they are the same.

Add a foregin key to a different table

I'm trying to add username from my st_accounts column into my table results using mySQL.
st_accounts table
`id` int(11) NOT NULL, //Primary Key
`firstname` varchar(50) NOT NULL,
`lastname` varchar(50) NOT NULL,
`username` varchar(50) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(100) NOT NULL,
`img` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
results table
`score_ID` int(11) NOT NULL, //Primary key
`score` int(20) NOT NULL,
`date` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I think you want:
create table accounts (
account_id int auto_increment primary key,
. . .
);
create table results (
result_id int auto_increment primary key,
account_id int not null
score int NOT NULL,
score_date date NOT NULL,
constraint fk_results_accounts foreig key (accounts_id) references accounts(account_id)
) ;
Notes:
Declare the primary key explicitly, not in a comment.
My convention is to name the primary key after the name of the table (in singular) with _id after it.
The foreign key has the same name as the primary key -- self documenting.
I made the integer primary keys auto_increment, so the database can assign unique values.

Create mysql table, parenthesis error: You have an error in your SQL syntax; check the manual ... for the right syntax to use near ')' at line 12

As a recent SQL learner, I've tried this piece of code for creating six tables through dozens of times, but cannot figure out what did the shell mean by saying that something is wrong near ")".
If there are obvious syntax errors, I could have fixed it.
Thank you for helping.
-- Table APPOINTMENT
CREATE TABLE APPOINTMENT (
AppointmentID INTEGER NOT NULL AUTO_INCREMENT,
DateAndTime VARCHAR(20) NULL DEFAULT NULL,
Venue VARCHAR(20) NULL DEFAULT NULL,
PatientName VARCHAR(20) NULL DEFAULT NULL,
DoctorName VARCHAR(20) NULL DEFAULT NULL,
PatientID VARCHAR(20) NOT NULL,
DoctorID VARCHAR(20) NOT NULL,
IsEmergency VARCHAR(3) DEFAULT "YES",
IsVisited VARCHAR(3) DEFAULT "YES",
PRIMARY KEY (AppointmentID),
);
-- Table PATIENT
CREATE TABLE PATIENT (
PatientID VARCHAR(20) NOT NULL,
PatientName VARCHAR(20) NULL DEFAULT NULL,
Address VARCHAR(20) NULL DEFAULT NULL,
CurrentMedication VARCHAR(20) NULL DEFAULT NULL,
ChronicDisease VARCHAR(20) NULL DEFAULT NULL,
Allergies VARCHAR(20) NULL DEFAULT NULL,
MedicalHistory VARCHAR(20) NULL DEFAULT NULL,
PRIMARY KEY (PatientID),
);
-- Table DOCTOR
CREATE TABLE DOCTOR (
DoctorID VARCHAR(20) NOT NULL,
DoctorName VARCHAR(20) NULL DEFAULT NULL,
PRIMARY KEY (DoctorID),
);
-- Table BILL
CREATE TABLE BILL (
AppointmentID INTEGER NOT NULL AUTO_INCREMENT,
DoctorID VARCHAR(20) NOT NULL,
PatientID VARCHAR(20) NOT NULL,
DateAndTime VARCHAR(20) NULL DEFAULT NULL,
Diagnosis VARCHAR(20) NULL DEFAULT NULL,
Treatment VARCHAR(20) NULL DEFAULT NULL,
Fees INTEGER NULL DEFAULT NULL,
ServiceCharge INTEGER NULL DEFAULT NULL,
ClaimId INTEGER NOT NULL,
InsuredDeduction INTEGER NULL AUTO_INCREMENT DEFAULT NULL,
ReceiptNumber INTEGER NOT NULL,
AmountPaid INTEGER NULL DEFAULT NULL,
TotalAmountDue INTEGER NULL DEFAULT NULL,
PRIMARY KEY (AppointmentID),
);
-- Table PAYMENT
CREATE TABLE PAYMENT (
ReceiptNumber INTEGER NOT NULL AUTO_INCREMENT,
AppointmentID INTEGER NOT NULL,
AmountPaid INTEGER NULL DEFAULT NULL,
PatientID VARCHAR(20) NOT NULL,
PRIMARY KEY (ReceiptNumber)
);
-- Table CLAIM
CREATE TABLE CLAIM (
ClaimId INTEGER NOT NULL AUTO_INCREMENT,
InsuranceCompanyName VARCHAR(20) NULL DEFAULT NULL,
PatientID VARCHAR(20) NOT NULL,
PRIMARY KEY (ClaimId),
);
-- Foreign Keys
ALTER TABLE APPOINTMENT ADD FOREIGN KEY (PatientID) REFERENCES PATIENT (PatientID);
ALTER TABLE APPOINTMENT ADD FOREIGN KEY (DoctorID) REFERENCES DOCTOR (DoctorID);
ALTER TABLE PAYMENT ADD FOREIGN KEY (AppointmentID) REFERENCES BILL (AppointmentID);
ALTER TABLE PAYMENT ADD FOREIGN KEY (PatientID) REFERENCES PATIENT (PatientID);
ALTER TABLE BILL ADD FOREIGN KEY (DoctorID) REFERENCES DOCTOR (DoctorID);
ALTER TABLE BILL ADD FOREIGN KEY (PatientID) REFERENCES PATIENT (PatientID);
ALTER TABLE BILL ADD FOREIGN KEY (ClaimId) REFERENCES CLAIM (ClaimId);
ALTER TABLE BILL ADD FOREIGN KEY (ReceiptNumber) REFERENCES PAYMENT (ReceiptNumber);
ALTER TABLE CLAIM ADD FOREIGN KEY (PatientID) REFERENCES PATIENT (PatientID);
You have an extra comma in every create table statement. eg PRIMARY KEY (DoctorID) has a trailing comma. MySql expects another column declaration after that comma.
-- Table DOCTOR
CREATE TABLE DOCTOR (
DoctorID VARCHAR(20) NOT NULL,
DoctorName VARCHAR(20) NULL DEFAULT NULL,
PRIMARY KEY (DoctorID)
);

relational database queries are not working mysql

I am trying to create a relational database in MySql but i am getting an error and I really cant figure out what’s wrong with my query.
Below is the error is get :
Error Code : 1072
Key column 'user_id' doesn't exist in table
(0 ms taken)
Here is my query :
CREATE TABLE tish_user(
user_id int(11) NOT NULL Auto_increment,
username varchar(30) NOT NULL,
Password varchar(41) NOT NULL,
Previllage VARCHAR(20) NOT NULL,
date_created datetime,
primary key (user_id )
)ENGINE=InnoDB;
CREATE TABLE tish_images(
image_id int(11) not null auto_increment,
image_name varchar(100) not null,
image_profile numeric(1) default 0,
FOREIGN KEY(user_id)REFERENCES tish_user(user_id)on update cascade,
primary key (image_id)
)ENGINE=InnoDB;
CREATE TABLE tish_clientinfor(
client_id int(11) not null auto_increment,
title varchar(11) not null,
firstname varchar(30) not null,
lastname varchar(30) not null,
client_code varchar(30) not null,
date_registered timestamp Default CURRENT_TIMESTAMP,
FOREIGN KEY(user_id)REFERENCES tish_user(user_id)on update cascade,
primary key (client_id)
)ENGINE=InnoDB;
You do not have a user_id column in tish_clientinfor as referenced by FOREIGN KEY(user_id).... Did you perhaps mean to add one?
CREATE TABLE tish_clientinfor(
client_id int(11) not null auto_increment,
title varchar(11) not null,
firstname varchar(30) not null,
lastname varchar(30) not null,
client_code varchar(30) not null,
date_registered timestamp Default CURRENT_TIMESTAMP,
user_id int(11) not null, --this was the missing column
FOREIGN KEY(user_id)REFERENCES tish_user(user_id)on update cascade,
primary key (client_id)
)ENGINE=InnoDB;
The same is true for table tish_images.