Creating nested triggers in MySQL - mysql

I am currently working with MySQL databases and I am trying to create a nested trigger. But I am having trouble and errors. I have tried many things but I cannot seem to figure out. Any help would be greatly appreciated. You would find my script for tables and trigger below.
CREATE TABLE co_op_members (
MemberID int not null AUTO_INCREMENT,
Description varchar(255),
BusinessName varchar(255),
Date date,
ContactName varchar(255),
Email varchar(255),
Phone int,
Address varchar(255),
PRIMARY KEY (MemberID)
);
CREATE TABLE Customers (
CustomerId int not null AUTO_INCREMENT,
Name varchar(255),
Email varchar(255),
Location varchar(255),
StartDate date,
DeliveryAddress varchar(255),
PRIMARY KEY (CustomerId)
);
CREATE TABLE Message (
MessageId int not null AUTO_INCREMENT,
CustomerId int ,
AepcMemberId int,
Message varchar(255),
Date date,
PRIMARY KEY (MessageId),
FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId),
FOREIGN KEY (AepcMemberId) REFERENCES co_op_members(MemberID)
);
CREATE TABLE Equipment (
ItemId int not null AUTO_INCREMENT,
StyleName varchar(255),
ItemName varchar(255),
PackSize int,
Description varchar(255),
MemberId int,
Price int,
PriceDate date,
UniteShippingDate date,
UnitShippingCost int,
PRIMARY KEY (ItemId),
FOREIGN KEY (MemberId) REFERENCES co_op_members(MemberId)
);
CREATE TABLE Equipmentorder (
OrderId int not null AUTO_INCREMENT,
CustomerId int,
AepcMemberId int,
ShippingDate date,
OrderStatus varchar(255),
OrderDate date,
CourierName varchar(255),
ItemId int,
ShippingCost float,
ShippingReferenceNo int,
PRIMARY KEY (OrderId),
FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId),
FOREIGN KEY (ItemId) REFERENCES Equipment(ItemId)
);
And here's the trigger script:
CREATE TRIGGER after_customer_order_plced
AFTER INSERT
ON message FOR EACH ROW
BEGIN
CREATE TRIGGER after_members_insert
AFTER INSERT
ON members FOR EACH ROW
BEGIN
IF NEW.customers IS NULL THEN
INSERT INTO message(memberId, message)
VALUES(new.id,CONCAT('Hi ', NEW.name, ', hello new message.'));
END
Thanks in advance for the help

Related

mysql error while creating table defining foreign keys

create database Geomart;
use geomart;
##Creating the table customers
create table customers (
CustomerID int not null,
Customer_Name varchar (20),
address varchar(50),
City varchar(20),
Postal_code int,
Country varchar(20),
primary key(CustomerID)
);
##Creating the Table Categories
create table Categories (
category_ID int not null,
Category_Name Varchar(20),
descriptions varchar(50),
primary key(Category_ID)
);
##Creating the table employees
create table employees (
employee_ID int not null,
Last_name Varchar(20),
First_Name varchar(20),
Bith_Date date,
Notes varchar(50),
primary key(employee_ID)
);
##Creating the table Shippers
Create table Shippers (
Shipper_ID int not null,
Shipper_name varchar(20),
phone int,
primary key(shipper_ID)
);
##Creating the table Orders - Error
create table orders (
order_ID int not null,
customerID int,
employee_ID int,
order_Date date,
Shipper_ID int,
primary key(order_ID),
foreign key(customerID) references customers,
foreign key(employee_ID) references employees,
foreign key(shipper_ID) references shippers
);
I am getting the error - Error Code: "1239. Incorrect foreign key definition for 'foreign key without name': Key reference and table reference don't match"
tried creating a table with multiple foreign keys in a single table. Is it possible

SQL Fiddle Giving "cannot add foreign key constraint" error

I am trying to figure out what is wrong with my syntax here. I feel like I have matched the examples I have found over the internet... but something must be amiss. Here is the code I am using. I keep getting the error code "cannot add Foreign Key constraint" when trying to run the build the schema.
CREATE TABLE Employe (
employee_id INT PRIMARY KEY,
first_name VARCHAR(30),
last_name VARCHAR(30),
hire_date DATE,
job_title VARCHAR(30),
shop_id INT,
FOREIGN KEY (shop_id) REFERENCES Coffee_Shop(shop_id)
);
CREATE TABLE Coffee_Shop (
shop_id INT PRIMARY KEY,
shop_name VARCHAR(50),
state CHAR(2),
);
CREATE TABLE Coffee (
coffee_id INT PRIMARY KEY,
shop_id INT,
supplier_id INT,
coffee_name VARCHAR(30),
price_per_pound NUMERIC(5,2),
FOREIGN KEY (shop_id) REFERENCES Coffee_Shop(shop_id),
FOREIGN KEY (supplier_id) REFERENCES Supplier(supplier_id)
);
CREATE TABLE Supplier (
supplier_id INT PRIMARY KEY,
company_name VARCHAR(50),
country VARCHAR(30),
sales_contact_name VARCHAR(60),
email VARCHAR(50) NOT NULL,
);
I just need to figure out what part of my foreign key is incorrectly defined. I know it normally results from an improperly defined primary key, but cannot seem to find where I messed up.
Thanks for your help
You are referencing a KEY that is not set up yet. SQL is linear, so the code gets executed line-by-line and cannot reference future lines (in most cases)
Create your tables in this order:
CREATE TABLE Coffee_Shop (
shop_id INT PRIMARY KEY,
shop_name VARCHAR(50),
state CHAR(2),
);
CREATE TABLE Supplier (
supplier_id INT PRIMARY KEY,
company_name VARCHAR(50),
country VARCHAR(30),
sales_contact_name VARCHAR(60),
email VARCHAR(50) NOT NULL,
);
CREATE TABLE Employe (
employee_id INT PRIMARY KEY,
first_name VARCHAR(30),
last_name VARCHAR(30),
hire_date DATE,
job_title VARCHAR(30),
shop_id INT,
FOREIGN KEY (shop_id) REFERENCES Coffee_Shop(shop_id)
);
CREATE TABLE Coffee (
coffee_id INT PRIMARY KEY,
shop_id INT,
supplier_id INT,
coffee_name VARCHAR(30),
price_per_pound NUMERIC(5,2),
FOREIGN KEY (shop_id) REFERENCES Coffee_Shop(shop_id),
FOREIGN KEY (supplier_id) REFERENCES Supplier(supplier_id)
);

Foreign key constraint is incorrectly formed in the table "Issues"

These are the two tables that I have created, but I get an error in the table issues:
I have searched up the internet but was unable to find any solution. Can you please help me in this.
CREATE TABLE Issues
(
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(100),
description TEXT,
type VARCHAR(50),
priority VARCHAR(50),
status VARCHAR(50),
assigned_to INT,
created_by INT,
created DATETIME,
updated DATETIME,
FOREIGN KEY (assigned_to, created_by) REFERENCES Users(id, id)
) ENGINE=InnoDB;
CREATE TABLE Users
(
id INT AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30),
lastname VARCHAR(30),
password VARCHAR(30),
email VARCHAR(30),
date_joined DATETIME
) ENGINE=InnoDB;
You want two foreign keys, not one - and you need to create the parent table before the child table:
-- parent table
create table users (
id int auto_increment primary key,
firstname varchar(30),
lastname varchar(30),
password varchar(30),
email varchar(30),
date_joined datetime
) engine=innodb;
-- child table
create table issues (
id int auto_increment primary key,
title varchar(100),
description text,
type varchar(50),
priority varchar(50),
status varchar(50),
assigned_to int,
created_by int,
created datetime,
updated datetime,
foreign key (assigned_to) references users(id), -- first FK
foreign key (created_by) references users(id) -- second FK
) engine=innodb;

Getting errors with my SQL database

I'm having trouble getting my SQL table to work. It keeps giving me an error that it cannot drop tables due to not permission or not exisiting. And it's telling me that there's an invalid table as well.
I currently have:
drop table Orders
drop table Item
drop table Supplier
drop table Staff
drop table Customers
drop table Ingredient
CREATE TABLE Supplier(
SupplierNo CHAR(7) PRIMARY KEY,
SupplierName CHAR(25),
SupplierAddress VARCHAR(25),
SupplierPhone CHAR(10),
SupplierContactPerson CHAR (35)
)
go
CREATE TABLE Item (
ItemNo CHAR(7) PRIMARY KEY,
ItemName CHAR(10),
ItemType CHAR(10),
Price DEC(3,2),
IngredientCode CHAR (5),
FOREIGN KEY(IngredientCode) REFERENCES Ingredient(IngredientCode)
)
go
CREATE TABLE Staff (
EmployeeID CHAR(3) PRIMARY KEY,
FirstName CHAR(10),
LastName CHAR(10),
PostalAddress VARCHAR(MAX),
ContactNumber CHAR (10),
RateOfPay MONEY,
EmployementStatus CHAR(25)
)
CREATE TABLE Customers (
CustomerID CHAR(4) PRIMARY KEY,
CustomerFN CHAR(25),
CustomerLN CHAR(25),
CustomerPhN CHAR(11),
CAddress VARCHAR (25)
)
go
CREATE TABLE Ingredient(
IngredientCode CHAR (5) PRIMARY KEY,
IngredientName CHAR(25),
IngredientDesc VARCHAR(max),
CurrentStockLevel CHAR(3),
PreviousStockLevel CHAR(3),
SuggestedStockLevel CHAR(3),
SupplierNo CHAR(7),
Supplied DATE(),
FOREIGN KEY(SupplierNo) REFERENCES Supplier(SupplierNo)
)
CREATE TABLE Orders(
OrderNo CHAR(7),
OrderDate DATE(),
CustomerNo CHAR(4) FOREIGN KEY,
EmployeeID CHAR(3) FOREIGN KEY,
ItemNo CHAR(7) FOREIGN KEY,
TypeOfOrder CHAR(10),
TotalAmount MONEY(),
PaymentMethod CHAR(10),
OrderStatus CHAR(10)
FOREIGN KEY CustomerNo, EmployeeID, ItemNo
REFERENCES Customer(CustomerNo), Staff(EmployeeID), Item(ItemNo)
)
It seems like a very simple problem to have, but I'm not even sure what it means with me having no permission or the table not existing at all...
You create constraint, before create table Ingredient
FOREIGN KEY(IngredientCode) REFERENCES Ingredient(IngredientCode)

MySQL Error 1217 [duplicate]

This question already has an answer here:
MySQL Error 1005?
(1 answer)
Closed 7 years ago.
I'm getting this error, and I know it's coming from the DROP TABLE IF statements, but I don't know how else to organize the drops for it to work. I've tried rearranging them but it won't work. The problem came when I introduced the Passenger table but I don't know how to fix it.
DROP TABLE IF EXISTS `Passenger`;
DROP TABLE IF EXISTS `ProductInvoice`;
DROP TABLE IF EXISTS `Invoice`;
DROP TABLE IF EXISTS `Product`;
DROP TABLE IF EXISTS `Customer`;
DROP TABLE IF EXISTS `Person`;
DROP TABLE IF EXISTS `Airport`;
DROP TABLE IF EXISTS `Address`;
DROP TABLE IF EXISTS `Email`;
CREATE TABLE Address
(
AddressID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(AddressID),
AddressStreet VARCHAR(255),
AddressCity VARCHAR(255),
AddressState VARCHAR(255),
AddressZip VARCHAR(255),
AddressCountry VARCHAR(255)
);
CREATE TABLE Email
(
EmailID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(EmailID),
EmailAddress VARCHAR(255)
);
CREATE TABLE Person
(
PersonID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PersonID),
PersonCode VARCHAR(255),
PersonLastName VARCHAR(255),
PersonFirstName VARCHAR(255),
AddressID INT NOT NULL,
FOREIGN KEY `fk_Person_to_Address` (AddressID) REFERENCES Address(AddressID),
PersonPhone VARCHAR(255),
EmailID INT NOT NULL,
FOREIGN KEY `fk_Person_to_Email` (EmailID) REFERENCES Email(EmailID)
);
CREATE TABLE Airport
(
AirportID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(AirportID),
AirportCode VARCHAR(255),
AirportName VARCHAR(255),
AddressID INT NOT NULL,
FOREIGN KEY `fk_Airport_to_Address` (AddressID) REFERENCES Address(AddressID),
AirportLatDeg INT NOT NULL,
AirportLatMin INT NOT NULL,
AirportLongDeg INT NOT NULL,
AirportLongMin INT NOT NULL,
AirportPassFacilityFee FLOAT NOT NULL
);
CREATE TABLE Customer
(
CustomerID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(CustomerID),
CustomerCode VARCHAR(255),
CustomerType VARCHAR(255),
PrimaryContact INT NOT NULL,
FOREIGN KEY `fk_Customer_to_Person` (PrimaryContact) REFERENCES Person(PersonID),
CustomerName VARCHAR(255),
CustomerAirlineMiles FLOAT NOT NULL
);
CREATE TABLE Product
(
ProductID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ProductID),
ProductCode VARCHAR(255),
ProductType VARCHAR(255),
DepAirportCode INT,
FOREIGN KEY `fk_Product_to_Airport` (DepAirportCode) REFERENCES Airport(AirportID),
ArrAirportCode INT,
FOREIGN KEY `frk_Product_to_Airport` (ArrAirportCode) REFERENCES Airport(AirportID),
DepartureTime VARCHAR(255),
ArrivalTime VARCHAR(255),
FlightNumber VARCHAR(255),
FlightClass VARCHAR(255),
AircraftType VARCHAR(255),
SeasonStartDate VARCHAR(255),
SeasonEndDate VARCHAR(255),
OffseasonRebate FLOAT,
AwardPointsPerMile FLOAT,
BaggageTicketCode INT,
FOREIGN KEY `fk_Product_to_Product` (BaggageTicketCode) REFERENCES Product(ProductID),
InsuranceName VARCHAR(255),
SpecialTypeOfService VARCHAR(255),
RefreshmentName VARCHAR(255),
RefreshmentCost FLOAT
);
CREATE TABLE Invoice
(
InvoiceID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(InvoiceID),
InvoiceCode VARCHAR(255),
CustomerCode INT NOT NULL,
FOREIGN KEY `fk_Invoice_to_Customer` (CustomerCode) REFERENCES Customer(CustomerID),
SalespersonCode INT NOT NULL,
FOREIGN KEY `fk_Invoice_to_Person` (SalespersonCode) REFERENCES Person(PersonID),
InvoiceDate VARCHAR(255)
);
CREATE TABLE ProductInvoice
(
ProductInvoiceID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ProductInvoiceID),
ProductID INT NOT NULL,
FOREIGN KEY `fk_ProductInvoice_to_Product` (ProductID) REFERENCES Product(ProductID),
InvoiceID INT NOT NULL,
FOREIGN KEY `fk_ProductInvoice_to_Invoice`(InvoiceID) REFERENCES Invoice(InvoiceID),
TravelDate VARCHAR(255),
NumOfPassengers INT NOT NULL,
Seat VARCHAR(255),
TicketNote VARCHAR(255)
);
CREATE TABLE Passenger
(
PassengerID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PassengerID),
PersonID INT NOT NULL,
FOREIGN KEY `fk_Passenger_to_Person` (PersonID) REFERENCES Person(PersonID),
IdentityNumber VARCHAR(255),
PassengerAge INT NOT NULL,
PassengerNationality VARCHAR(255),
ProductInvoiceID INT NOT NULL,
FOREIGN KEY `fk_Passenger_to_ProductInvoice` (ProductInvoiceID)
REFERENCES ProductInvoice(ProductInvoiceID)
);
This is the error I get:
Error Code: 1217. Cannot delete or update a parent row: a foreign key constraint fails
and it fails on the DROP TABLE for Invoice.
Disable foreign key checks or.
Drop the whole database or.
Run the script twice or.
Drop the fk constraints first.
Mysql workbench will generate a script for you if you highlight all if the tables and create a drop script. Same with the mysql dump utility.
How to temporarily disable a foreign key constraint in MySQL?