Booking limitation with check SQL - mysql

I want to set a constraint where a person IS NOT ALLOWED TO book a certain car, if it is already booked. I'm a bit of a beginner therefore I wonder if check/trigger would be an idea for this problem. E.g.
ALTER TABLE bookings
ADD CHECK (vehicle_id = NOT NULL)
The tables are
CREATE TABLE customers (
customer_id int(50) NOT NULL AUTO_INCREMENT,
fname varchar(20) NOT NULL,
lname varchar(20) NOT NULL,
dateOfBirth date NOT NULL,
address varchar(30) NOT NULL,
city varchar(20) NOT NULL,
county ENUM('Armagh','Carlow','Cavan','Clare','Cork','Derry','Donegal','Down','Dublin','Fermanagh','Galway','Kerry','Kildare','Kilkenny','Laois','Leitrim','Limerick','Longford','Louth','Mayo','Meath','Monaghan','Offaly','Roscommon','Sligo','Tipperary','Tyrone','Waterford','Westmeath','Wexford','Wicklow') NOT NULL,
phone int(10) NOT NULL,
email varchar(20) NOT NULL,
payment_method ENUM ('Visa', 'Amex', 'Cash', 'American Express', 'Mastercard') NOT NULL,
valid_licence varchar(5) NOT NULL,
status varchar(10),
PRIMARY KEY (customer_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE vehicles (
vehicle_id int(10) NOT NULL AUTO_INCREMENT,
category ENUM('Sedan','Hatchback','SUV', 'Coupe', 'Crossover') NOT NULL,
no_of_seats int(11) NOT NULL,
brand varchar(20) NOT NULL,
model varchar(20) NOT NULL,
product_year int(5) NOT NULL,
rate_per_day int(11) NOT NULL,
PRIMARY KEY (vehicle_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE vehicle_collections (
collection_id int(10)NOT NULL AUTO_INCREMENT,
vehicle_id int(10) NOT NULL ,
collection_date date NOT NULL,
return_date date NOT NULL,
mileage_before int(10) NOT NULL,
mileage_after int(10) NOT NULL,
duration int(5) NOT NULL,
PRIMARY KEY (collection_id),
KEY vehicle_idfk1 (vehicle_id),
CONSTRAINT vehicle_idfk1 FOREIGN KEY (vehicle_id) REFERENCES vehicles (vehicle_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE bookings (
booking_id int(50) NOT NULL AUTO_INCREMENT,
booking_date date NOT NULL,
start_date date NOT NULL,
end_date date NOT NULL,
invoice_no int(10) NOT NULL ,
chauffeur_id int(10) NULL,
vehicle_id int(10) NOT NULL ,
customer_id int(50) NOT NULL ,
chauffeur_req ENUM('Yes','No') NOT NULL,
special_instructions varchar(255) NOT NULL,
PRIMARY KEY (booking_id),
KEY invoice_nofk2 (invoice_no),
KEY chauffeur_idfk1 (chauffeur_id),
KEY customer_idfk2 (customer_id),
KEY vehicle_idfk2 (vehicle_id),
CONSTRAINT invoice_nofk1 FOREIGN KEY (invoice_no) REFERENCES invoice (invoice_no),
CONSTRAINT chauffeur_idfk2 FOREIGN KEY (chauffeur_id) REFERENCES chauffeurs (chauffeur_id),
CONSTRAINT customer_idfk3 FOREIGN KEY (customer_id) REFERENCES customers (customer_id),
CONSTRAINT vehicle_idfk3 FOREIGN KEY (vehicle_id) REFERENCES vehicles (vehicle_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Here is my table structure if it will help. I think of using a check but one of main problems is - How do you say in MySQL language that ' if a car is booked?' . Trigger?

Related

Adding data into myadminPhp

Hey guys so Im trying to add some data into my tables, for some reason the inspection table wouldnt allow to add data to itself. Im uploading it as SQL file because I used mockaroo for dummy data!
/*
-- Use test;
-- Use mysql;
-- Use information_schema;
-- source f:/createempdepttable.sql;
-- Notice the forward slash / in above statement
*/
-- section 13.1.28. MySQL Documentation DROP TABLE Syntax
Drop database if exists g00337857abu;
create database g00337857abu CHARACTER SET utf8 COLLATE UTF8_GENERAL_CI ;
Use g00337857abu;
Show tables;
DROP TABLE IF EXISTS invoice;
CREATE TABLE invoice (
invoice_no int(10) NOT NULL AUTO_INCREMENT,
date date NOT NULL,
PRIMARY KEY(invoice_no)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS chauffeurs;
CREATE TABLE chauffeurs (
chauffeur_id int(10) NOT NULL,
fname varchar(20) NOT NULL,
lname varchar(20) NOT NULL,
phone int(15) NOT NULL,
address varchar(20) NOT NULL,
city varchar(15) NOT NULL,
county varchar(15) NOT NULL,
PRIMARY KEY (chauffeur_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS customers;
CREATE TABLE customers (
customer_id int(50) NOT NULL AUTO_INCREMENT,
fname varchar(20) NOT NULL,
lname varchar(20) NOT NULL,
address varchar(30) NOT NULL,
city varchar(20) NOT NULL,
county ENUM('Armagh','Carlow','Cavan','Clare','Cork','Derry','Donegal','Down','Dublin','Fermanagh','Galway','Kerry','Kildare','Kilkenny','Laois','Leitrim','Limerick','Longford','Louth','Mayo','Meath','Monaghan','Offaly','Roscommon','Sligo','Tipperary','Tyrone','Waterford','Westmeath','Wexford','Wicklow') NOT NULL,
phone int(10) NOT NULL,
email varchar(20) NOT NULL,
payment_method ENUM ('Visa', 'Amex', 'Cash', 'American Express', 'Mastercard') NOT NULL,
status ENUM('Approved','Unapproved'),
driver_no varchar(20),
PRIMARY KEY (customer_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS mechanics;
CREATE TABLE mechanics (
mechanic_id int(10) NOT NULL AUTO_INCREMENT,
fname varchar(20) NOT NULL,
lname varchar(20) NOT NULL,
PRIMARY KEY (mechanic_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS vehicles;
CREATE TABLE vehicles (
vehicle_id int(10) NOT NULL AUTO_INCREMENT,
category ENUM('Sedan','Hatchback','SUV', 'Coupe', 'Crossover') NOT NULL,
no_of_seats int(11) NOT NULL,
brand varchar(25) NOT NULL,
model varchar(25) NOT NULL,
product_year int(11) NOT NULL,
rate_per_day int(11) NOT NULL,
PRIMARY KEY (vehicle_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS inspections;
CREATE TABLE inspections (
inspection_id int(10) NOT NULL AUTO_INCREMENT,
inspection_date date NOT NULL,
vehicle_id int(10) NOT NULL,
problem varchar(50) NOT NULL,
repair varchar(55) NOT NULL,
repair_complete ENUM('Yes','No') NOT NULL,
mechanic_id int(10) NOT NULL,
PRIMARY KEY(inspection_id),
KEY mechanic_idfk1 (mechanic_id),
KEY vehicle_idfk2 (vehicle_id),
CONSTRAINT vehicle_idfk2 FOREIGN KEY (vehicle_id) REFERENCES vehicles (vehicle_id),
CONSTRAINT mechanic_idfk1 FOREIGN KEY (mechanic_id) REFERENCES mechanics (mechanic_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS payment_details;
CREATE TABLE payment_details (
card_no int(50) NOT NULL AUTO_INCREMENT,
customer_id int(50) NOT NULL,
CVV int(11) NOT NULL,
card_type ENUM('Visa', 'Amex', 'Cash', 'Mastecard') NOT NULL,
expiry_date date NOT NULL,
PRIMARY KEY(card_no),
KEY customer_idfk1 (customer_id),
CONSTRAINT customer_idfk1 FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS vehicle_collections;
CREATE TABLE vehicle_collections (
collection_id int(10) NOT NULL AUTO_INCREMENT,
vehicle_id int(10) NOT NULL,
collection_date date NOT NULL,
return_date date NOT NULL,
mileage_before int(10) NOT NULL,
mileage_after int(10) NOT NULL,
duration int(5) NOT NULL,
PRIMARY KEY (collection_id),
KEY vehicle_idfk1 (vehicle_id),
CONSTRAINT vehicle_idfk1 FOREIGN KEY (vehicle_id) REFERENCES vehicles (vehicle_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS bookings;
CREATE TABLE bookings (
booking_id int(50) NOT NULL AUTO_INCREMENT,
booking_date date NOT NULL,
start_date date NOT NULL,
end_date date NOT NULL,
invoice_no int(10) NOT NULL,
chauffeur_id int(10)NOT NULL,
vehicle_id int(10) NOT NULL,
customer_id int(50) NOT NULL,
chauffeur_req ENUM('Yes','No') NOT NULL,
PRIMARY KEY (booking_id),
KEY invoice_nofk2 (invoice_no),
KEY chauffeur_idfk1 (chauffeur_id),
KEY customer_idfk2 (customer_id),
KEY vehicle_idfk2 (vehicle_id),
CONSTRAINT invoice_nofk1 FOREIGN KEY (invoice_no) REFERENCES invoice (invoice_no) ON DELETE CASCADE,
CONSTRAINT chauffeur_idfk2 FOREIGN KEY (chauffeur_id) REFERENCES chauffeurs (chauffeur_id)ON DELETE CASCADE,
CONSTRAINT customer_idfk3 FOREIGN KEY (customer_id) REFERENCES customers (customer_id) ON DELETE CASCADE,
CONSTRAINT vehicle_idfk3 FOREIGN KEY (vehicle_id) REFERENCES vehicles (vehicle_id)ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
error in php is as follows:
1452 - Cannot add or update a child row: a foreign key constraint fails (g00337857abu.inspections, CONSTRAINT mechanic_idfk1 FOREIGN KEY (mechanic_id) REFERENCES mechanics (mechanic_id))
could it be because mechanic table isnt yet filled out? I only filled out chauffeurs customers so far and they were fine

Adding Foreign key but getting constraint violation error

I have four tables:
1)Country:Two columns
a) country_id
b) country_name
2)State: Three columns
a) state_id
b) state_name
c) country_id(foreign key)
3)City: Three Columns
a) city_id
b) city_name
c) state_id(foreign key)
4) Doctor: 20 Columns
a) doc_id (primary key)
b) doc_name
c) email,gender age and so on
I have populated these tables with dara.
I am adding three new columns: country_id, state_id and city_id in doctor table as a foreign key.
When I insert the country_id, state_id and city_id as a foreign key in that table I got this error
1452 - Cannot add or update a child row: a foreign key constraint fails (`medical_network`.`#sql-4174_45`, CONSTRAINT `#sql-4174_45_ibfk_1` FOREIGN KEY (`country_id`) REFERENCES `country` (`country_id`) ON DELETE CASCADE ON UPDATE CASCADE)
I know this is a basic error, but can't find the mistake.
Doctor Table:
CREATE TABLE `doctor` (
`doc_id` int(9) NOT NULL AUTO_INCREMENT,
`doc_fname` varchar(15) NOT NULL,
`doc_lname` varchar(15) NOT NULL,
`doc_province` varchar(20) NOT NULL,
`doc_city` varchar(25) NOT NULL,
`doc_gender` varchar(10) NOT NULL,
`doc_fathername` varchar(32) NOT NULL,
`doc_age` varchar(20) NOT NULL,
`doc_cnic` varchar(16) NOT NULL,
`doc_medclgname` varchar(100) NOT NULL,
`doc_specilization` varchar(100) NOT NULL,
`doc_phoneno` varchar(20) NOT NULL,
`doc_officeno` varchar(20) NOT NULL,
`doc_email` varchar(25) NOT NULL,
`doc_gradyear` int(10) NOT NULL,
`doc_licenseno` varchar(30) NOT NULL,
`doc_hosp` varchar(200) NOT NULL,
`doc_pass` varchar(35) NOT NULL,
`doc_address` varchar(100) NOT NULL,
`doc_country` varchar(100) NOT NULL,
`doc_img` varchar(200) NOT NULL,
`totime` time NOT NULL,
`fromtime` time NOT NULL,
`todate` date NOT NULL,
`fromdate` date NOT NULL,
`country_id` int(20) NOT NULL,
PRIMARY KEY (`doc_id`),
KEY `country_id` (`country_id`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=latin
Country Table:
CREATE TABLE `country` (
`country_id` int(20) NOT NULL AUTO_INCREMENT,
`country_name` varchar(200) NOT NULL,
PRIMARY KEY (`country_id`)
) ENGINE=InnoDB AUTO_INCREMENT=252 DEFAULT CHARSET=latin1
State Table Query:
CREATE TABLE `state` (
`state_id` int(20) NOT NULL AUTO_INCREMENT,
`state_name` varchar(200) NOT NULL,
`country_id` int(20) NOT NULL,
PRIMARY KEY (`state_id`),
KEY `country_id` (`country_id`),
CONSTRAINT `state_ibfk_1` FOREIGN KEY (`country_id`) REFERENCES `country` (`country_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1
City Table:
CREATE TABLE `city` (
`city_id` int(20) NOT NULL AUTO_INCREMENT,
`city_name` varchar(200) NOT NULL,
`state_id` int(20) NOT NULL,
PRIMARY KEY (`city_id`),
KEY `state_id` (`state_id`),
CONSTRAINT `city_ibfk_1` FOREIGN KEY (`state_id`) REFERENCES `state` (`state_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1
First Add All the columns you want to make foreign keys in the Table.
Add some relevant data into it.
Now Alter the table and make those new added column a foreign key.
ie
ALTER TABLE TblName
AD FOREIGN KEY (P_Id)
REFERENCES ParentTable(P_Id)
In English:
You have some doctors who are in unknown countries.
In DB-speak:
One or more rows of doctor have a value for country_id that in not found in the country_id column of country.
Check that the values of country_id for new doctor rows exist in the country table.
To find them if doctor rows already exist:
select d.*
from doctor d
left join country c on c.country_id = doctor.country_id
where c.country_id is null
Change the column country_id int(20) NULL in 'doctor' table

Cannot add foreign key constraint with foreign key being primary

I am getting the
Error Code: 1215. Cannot add foreign key constraint 0.172 sec
I don't know what I am doing wrong. I made sure that the foreign key is a primary key.
My sql:
CREATE TABLE Student (
StudentID INT(6) NOT NULL,
StudName VARCHAR(15) NOT NULL,
StudEmail VARCHAR(15) NOT NULL,
StudeHomeNum INT(10) NOT NULL,
StudCellPhoneNum INT(10) NOT NULL,
CourseCode INT(6) NOT NULL,
ProgramCode INT(6) NOT NULL,
PRIMARY KEY (StudentID),
FOREIGN KEY (CourseCode)
REFERENCES Course (CourseCode)
);
CREATE TABLE Course (
CourseCode INT(6) PRIMARY KEY NOT NULL,
CourseName VARCHAR(15) NOT NULL,
Prequisites VARCHAR(15) NOT NULL
);
Since CourseCode code column in Student table is referencing Course table, you have to create Course table first. Change your sql code as below
CREATE TABLE Course (
CourseCode INT(6) PRIMARY KEY NOT NULL,
CourseName VARCHAR(15) NOT NULL,
Prequisites VARCHAR(15) NOT NULL
);
CREATE TABLE Student (
StudentID INT(6) NOT NULL,
StudName VARCHAR(15) NOT NULL,
StudEmail VARCHAR(15) NOT NULL,
StudeHomeNum INT(10) NOT NULL,
StudCellPhoneNum INT(10) NOT NULL,
CourseCode INT(6) NOT NULL,
ProgramCode INT(6) NOT NULL,
PRIMARY KEY (StudentID),
FOREIGN KEY (CourseCode)
REFERENCES Course (CourseCode)
);

Creating a table with foreign keys shows an error

I'm trying to create a table and am getting an error telling me there's something wrong around line 9. This is the code.
CREATE TABLE shirts_link (
adult VARCHAR(1) NOT NULL,
kids VARCHAR(1) NOT NULL,
babies VARCHAR(1) NOT NULL,
shirt_id INT(4) NOT NULL,
size_id INT(4) NOT NULL,
price_id INT(4) NOT NULL,
PRIMARY KEY (shirt_id,size_id,price_id),
FOREIGN KEY (shirt_id) REFERENCES shirts(id),
FOREIGN KEY (size_id) REFERENCES shirt_sizes(id),
FOREIGN KEY (price_id) REFERENCES shirt_prices(id)
)ENGINE=INNODB;
here's the other tables I'm trying to link to..
CREATE TABLE shirts (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY NOT NULL,
shirt_name VARCHAR(20) NOT NULL,
men VARCHAR(10) NULL,
women VARCHAR(10) NULL,
boys VARCHAR(10) NULL,
girls VARCHAR(10) NULL,
babies VARCHAR(10) NULL,
)ENGINE=INNODB;
CREATE TABLE shirt_sizes (
id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
size_name VARCHAR(10) NOT NULL
)ENGINE=INNODB;
CREATE TABLE shirt_prices (
id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
price_cat VARCHAR(10) NOT NULL,
price NUMERIC(6,2) NOT NULL
)ENGINE=INNODB;
the problem is that you are wrapping table names and column names with single quotes. it shouldn't be or use backtick instead
FOREIGN KEY (shirt_id) REFERENCES shirts(id),
FOREIGN KEY (size_id) REFERENCES shirt_sizes(id),
FOREIGN KEY (price_id) REFERENCES shirt_prices(id)
or
FOREIGN KEY (`shirt_id`) REFERENCES `shirts`(`id`),
FOREIGN KEY (`size_id`) REFERENCES `shirt_sizes`(`id`),
FOREIGN KEY (`price_id`) REFERENCES `shirt_prices`(`id`)
but in this case, they are optional since non of they are MySQL reserved Keywords.
MySQL Reserved Keywords List
UPDATE 1
The data type of the keys must be the same with each other, declare these columns as UNSIGNED
shirt_id INT(4) UNSIGNED NOT NULL,
size_id INT(4) UNSIGNED NOT NULL,
price_id INT(4) UNSIGNED NOT NULL,
SQLFiddle Demo
CREATE TABLE shirts_link (
adult VARCHAR(1) NOT NULL,
kids VARCHAR(1) NOT NULL,
babies VARCHAR(1) NOT NULL,
shirt_id INT(4) NOT NULL,
size_id INT(4) NOT NULL,
price_id INT(4) NOT NULL,
PRIMARY KEY (shirt_id,size_id,price_id),
FOREIGN KEY (shirt_id) REFERENCES shirts(id),
FOREIGN KEY (size_id) REFERENCES shirt_sizes(id),
FOREIGN KEY (price_id) REFERENCES shirt_prices(id)
)ENGINE=INNODB;
it worked for me on sqlfiddle
Here is my code:
CREATE TABLE shirts(
id INT NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE shirts_link (
adult VARCHAR(1) NOT NULL,
kids VARCHAR(1) NOT NULL,
babies VARCHAR(1) NOT NULL,
shirt_id INT(4) NOT NULL,
size_id INT(4) NOT NULL,
price_id INT(4) NOT NULL,
PRIMARY KEY (shirt_id,size_id,price_id),
FOREIGN KEY (shirt_id) REFERENCES shirts(id)
);

Duplicate key name 'unique_id'

Here is the sql, however, there is an error says "*#1061 - Duplicate key name 'unique_id'* ", what is the problem.
create table `users`(
uid int(11) auto_increment,
unique_id varchar(23) not null unique,
name varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null,
PRIMARY KEY (`unique_id`),
UNIQUE KEY `uid` (`uid`),
UNIQUE KEY `unique_id` (`unique_id`),
UNIQUE KEY `email` (`email`)
)ENGINE=InnoDB AUTO_INCREMENT=877888 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
remove this line
UNIQUE KEY `unique_id` (`unique_id`),
since unique_id is already Primary Key. and Primary Keys are unique.
full CREATE TABLE statement
create table `users`
(
uid int(11) auto_increment,
unique_id varchar(23) not null,
name varchar(50) not null,
email varchar(100) not null unique, -- specified here
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null,
PRIMARY KEY (`unique_id`),
UNIQUE KEY `uid` (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=877888
DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
SQLFiddle Demo