relational database queries are not working mysql - 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.

Related

Error number: 3780 Referencing column '%s' and referenced column '%s' in foreign key constraint '%s' are incompatible

DROP DATABASE IF EXISTS ProviderPatients;
CREATE DATABASE ProviderPatients;
USE ProviderPatients;
CREATE TABLE IF NOT EXISTS Date_Dim
(
Date_ID integer not null,
Date_ date,
Full_Date_Des varchar(25) not null,
Day_Of_Week int(11) not null,
Calender_Year int(11) not null,
Weekday_Indicator int(11) not null,
PRIMARY KEY (Date_ID)
);
CREATE TABLE IF NOT EXISTS Insurer_DIM
(
Insurer_ID int(11) not null,
Insurer_Name varchar(25) not null,
Line_Of_Buissness varchar(25) not null,
PRIMARY KEY (Insurer_ID)
);
CREATE TABLE IF NOT EXISTS Member_DIM
(
Member_ID int(11) not null,
Member_Name varchar(25) not null,
Age int(11) not null,
Ethnicity varchar(25) not null,
Health_Condition varchar(25) not null,
PRIMARY KEY (Member_ID)
);
CREATE TABLE IF NOT EXISTS Geography_Dim
(
Geography_ID varchar(25) not null,
Country varchar(25) not null,
State varchar(10) not null,
State_Code int(11) not null,
County_Code int(11) not null,
PRIMARY KEY (Geography_ID)
);
CREATE TABLE Provider_Dim
(
Provider_ID int(11) not null,
Provider_Name VARCHAR(45) NOT NULL,
Gender Varchar(25) Not Null,
NPI Varchar(25) Not Null,
Credential Varchar(25) Not Null,
PRIMARY KEY(Provider_ID)
);
CREATE TABLE Eval_Fact_Table
(
Date_ID int(11) not null,
Member_ID int(11) not null,
Provider_ID int(11) not null,
Insurer_ID int(11) not null,
Geography_ID int(11) not null,
Num_Visits int(11) not null,
Eval_Costint int(11) not null,
Eval_Start date not null,
Eval_End date not null,
FOREIGN KEY (Date_ID)
REFERENCES Date_Dim (Date_Id) ON DELETE RESTRICT,
FOREIGN KEY (Member_ID)
REFERENCES Member_Dim (Member_ID) ON DELETE RESTRICT,
FOREIGN KEY (Geography_ID)
REFERENCES Geography_Dim (Geography_ID) ON DELETE RESTRICT,
FOREIGN KEY (Provider_ID)
REFERENCES Proveider_Dim (Provider_ID) ON DELETE RESTRICT,
FOREIGN KEY (Insurer_ID)
REFERENCES Insurer_Dim (Insurer_ID) ON DELETE RESTRICT
);
Error number: 3780; Symbol: ER_FK_INCOMPATIBLE_COLUMNS; SQLSTATE: HY000
Message:Error Code: 3780. Referencing column 'Geography_ID' and referenced column 'Geography_ID' in foreign key constraint 'eval_fact_table_ibfk_3' are incompatible.
Error Referencing column 'Geography_ID' and referenced column 'Geography_ID' in foreign key constraint 'eval_fact_table_ibfk_3' are incompatible.
is quite clear, columns are incompatible:
CREATE TABLE IF NOT EXISTS Geography_Dim (
Geography_ID varchar(25) not null,
CREATE TABLE Eval_Fact_Table(
... truncated
Geography_ID int(11) not null,
Make them of same type or remove foreign key constraint.
You can read more about foreign key constraints in documentation, most interesting part is
Corresponding columns in the foreign key and the referenced key must
have similar data types.
That is not true in your case : varchar(25) vs. int(11)
I tried all other ways but I found this useful as it worked for me. It is applicable also to the new MySQL version(v8.0)
CREATE TABLE Customers(
Customers_ID INT(10) PRIMARY KEY AUTO_INCREMENT,
Customers_name varchar(40) not null,
Customers_phone INT(10) not null,
Customers_email varchar(40) not null,
date_became_customer DATE not null,
login varchar(40) not null,
password varchar(40) not null,
other_details varchar(40) not null,
Customer_Types_code int(10) not null
REFERENCES Customer_types(Customer_Types_code));
Just change Geograpy_ID on Geography_Dim table to Geography_ID int(11) or change Geograpy_ID on Eval_Fact_Table to Geography_ID varchar(25) to solve the problem.
Error number: 3780 is due to incompatible foreign keys, the datatype of foreign key in each table must be same .
You could also not edit the primary key column in one table if it is a foreign key in another table.
For editing first drop the foreign key constraint in child table and then edit the primary key in the parent table and then again add constraints to child table.
HERE: Geography_ID varchar(25) vs Geography_ID int(11) are incompatible
First drop or alter this
FOREIGN KEY (Geography_ID) REFERENCES Geography_Dim (Geography_ID)
Geography_ID int(11) NOT NULL, and then add new column:
FOREIGN KEY (Geography_ID) REFERENCES Geography_Dim (Geography_ID)
with Geography_ID varchar(25)

Many-to-many relationship: how to delete records from 3 table?

For example, I have the following tables:
person person_address address
========== ================== ===========
pid (PK) pid (FK) aid (PK)
... aid (FK) ...
I've set pid to ON DELETE CASCADE and aid to ON DELETE NO ACTION. The goal is to delete the according record from address if a person gets deleted.
I have tried trigger:
CREATE TRIGGER pa_delete
AFTER DELETE ON person_address
FOR EACH ROW
DELETE FROM address
WHERE person_address.address_id = address.address_id
But when I delete the person record, address record is still there. What am I doing wrong?
EDIT
Tables involved:
CREATE TABLE IF NOT EXISTS `chkdcrm`.`person` (
`person_id` INT(11) NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(45) NOT NULL,
`last_name` VARCHAR(45) NOT NULL,
`tel` VARCHAR(20) NULL,
`fax` VARCHAR(20) NULL,
`mobile` VARCHAR(20) NOT NULL UNIQUE,
`email` VARCHAR(150) NOT NULL UNIQUE,
PRIMARY KEY (`person_id`))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `chkdcrm`.`address` (
`address_id` INT(11) NOT NULL AUTO_INCREMENT,
`type` ENUM('Invoice', 'Shipping', 'Site', 'Mailing') NOT NULL,
`street` VARCHAR(100) NOT NULL,
`city` VARCHAR(100) NOT NULL,
`state` VARCHAR(30) NOT NULL,
`zip` VARCHAR(10) NOT NULL,
`country` VARCHAR(40) NOT NULL,
PRIMARY KEY (`address_id`))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `chkdcrm`.`person_address` (
`address_id` INT(11) NOT NULL,
`person_id` INT(11) NOT NULL,
PRIMARY KEY (`address_id`, `person_id`),
CONSTRAINT `fk_pa_address`
FOREIGN KEY (`address_id`)
REFERENCES `chkdcrm`.`address` (`address_id`)
ON DELETE NO ACTION,
CONSTRAINT `fk_pa_person`
FOREIGN KEY (`person_id`)
REFERENCES `chkdcrm`.`person` (`person_id`)
ON DELETE CASCADE)
ENGINE = InnoDB;

Why I obtain this FK error when I try to create this table? errno: 150 "Foreign key constraint is incorrectly formed

I have this USER table on a MySql DB:
id bigint(20) unsigned NO PRI NULL auto_increment
username varchar(30) NO NULL
pswd varchar(40) NO NULL
Then I am trying to create a new ACCOMODATION table having a user_Id field that is the foreign key of the previous USER table, I am doing in this way:
CREATE
TABLE testdb.ACCOMODATION
(
Id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
user_Id BIGINT(20) NOT NULL,
name VARCHAR(255) NOT NULL,
address VARCHAR(255) NOT NULL,
tel VARCHAR(20) NOT NULL,
mobile VARCHAR(20) NOT NULL,
fax VARCHAR(20) NOT NULL,
email VARCHAR(80) NOT NULL,
cap VARCHAR(20) NOT NULL,
nation VARCHAR(20) NOT NULL,
region VARCHAR(20) NOT NULL,
province VARCHAR(20) NOT NULL,
municipality VARCHAR(20) NOT NULL,
stars ENUM('ONE', 'TWO', 'THREE', 'FOUR', 'FIVE') NOT NULL,
lat BIGINT NOT NULL,
lon BIGINT NOT NULL,
CONSTRAINT fk_accomodation_user FOREIGN KEY (user_Id) REFERENCES testdb.user (Id),
PRIMARY KEY (Id)
)
ENGINE=InnoDB DEFAULT CHARSET=latin1
But I obtain the following error message:
#1005 - Can't create table testdb.accomodation (errno: 150 "Foreign key constraint is incorrectly formed")
How can I fix this issue?
Data type of user_id column in ACCOMODATION table must be exactly the same data type of id column in user table.
user_id bigint(20) unsigned NO NULL
These definitions are not the same:
id bigint(20) unsigned NO PRI NULL auto_increment
user_Id BIGINT(20) NOT NULL
An unsigned bigint is not the same as a signed bigint. The columns used in a foreign key reference need to have exactly the same types as the columns in the original table.

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)
);

ERROR 1215: Cannot add foreign key constraint when using ON DELETE SET NULL

I'm trying to create the following tables in MySQL. The first one:
CREATE TABLE IF NOT EXISTS address(
address_id INT NOT NULL AUTO_INCREMENT,
address_region VARCHAR(10) NOT NULL,
address_country VARCHAR(20) NOT NULL,
address_city VARCHAR(30) NOT NULL,
PRIMARY KEY(address_id))ENGINE = InnoDB;
I created it successfully,but when I try to create another table as following
CREATE TABLE IF NOT EXISTS spot(
spot_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
spot_address INT(11) NOT NULL,
spot_name VARCHAR(50) NOT NULL,
spot_desc VARCHAR(500) DEFAULT ' ',
spot_speadd VARCHAR(100) NOT NULL,
spot_viewtime INT DEFAULT 0,
FOREIGN KEY(spot_address)
REFERENCES address(address_id)
ON DELETE SET NULL
ON UPDATE SET NULL);
I get an error:
ERROR 1215 (HY000): Cannot add foreign key constraint
Why is this create table statement failing?
You have NOT NULL constraint on spot_address in the spot table and then try to set it to NULL on delete or update in the parent table address.
You can try this:
CREATE TABLE IF NOT EXISTS address
(
address_id INT NOT NULL AUTO_INCREMENT,
address_region VARCHAR(10) NOT NULL,
address_country VARCHAR(20) NOT NULL,
address_city VARCHAR(30) NOT NULL,
PRIMARY KEY(address_id)
)ENGINE = INNODB;
CREATE TABLE IF NOT EXISTS `spot`
(
`spot_id` INT(11) NOT NULL AUTO_INCREMENT,
`spot_address` INT(11) NOT NULL,
`spot_name` VARCHAR(50) NOT NULL,
`spot_desc` VARCHAR(500) DEFAULT ' ',
`spot_speadd` VARCHAR(100) NOT NULL,
`spot_viewtime` INT(11) DEFAULT '0',
PRIMARY KEY (`spot_id`),
KEY `spot_address` (`spot_address`),
CONSTRAINT `spot_ibfk_1` FOREIGN KEY (`spot_address`) REFERENCES `address` (`address_id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8