Trigger for last inserted value - mysql

can anyone help me create a trigger that appends the last record from table Sensordata into Lastsensordata. I only want 1 value per ConnectionDeviceId and the value needs to be the last inserted one. (its going to be used to show in a gauge). I will link my sql script under.
CREATE TABLE Revpi (
revpiName varchar(100) NOT NULL,
revpiDateTimeCreated datetime NOT NULL,
revpiLocation varchar(150) NOT NULL,
CONSTRAINT PK_revpiNavn PRIMARY KEY (revpiName)
);
CREATE TABLE Sensor (
sensorName varchar(100) NOT NULL,
revpiName varchar(100) NOT NULL,
sensorDateTimeCreated datetime NOT NULL,
CONSTRAINT PK_sensorNavn PRIMARY KEY (sensorName),
CONSTRAINT FK_revpiName FOREIGN KEY (revpiName) REFERENCES Revpi (revpiName)
);
CREATE TABLE Sensordata (
SensordataID int NOT NULL AUTO_INCREMENT,
data varchar (500),
ConnectionDeviceId varchar(500) NOT NULL,
EventProcessedUtcTime varchar(50) NOT NULL,
CONSTRAINT PK_sensorDataNavn PRIMARY KEY (SensordataID),
CONSTRAINT FK_sensorNavn FOREIGN KEY (ConnectionDeviceId) REFERENCES Sensor (sensorName)
);
CREATE TABLE Lastsensordata (
lastSensorNavn varchar(255) NOT NULL,
lastData varchar (500) NOT NULL,
LastTime varchar(50) NOT NULL,
CONSTRAINT PK_Lastsensordata PRIMARY KEY (lastSensorNavn),
CONSTRAINT FK_LastensordataSensordata FOREIGN KEY (lastSensorNavn) REFERENCES Sensordata (ConnectionDeviceId)
);

You can do it with the following trigger:
CREATE TRIGGER after_insert_sensordata
AFTER INSERT ON Sensordata
FOR EACH ROW
REPLACE INTO Lastsensordata VALUES (NEW.ConnectionDeviceId, NEW.`data`, NEW.EventProcessedUtcTime);
You will need to make the lastSensorNavn field unique. You should also fix the varchar size discrepancy between lastsensornavn and connectiondeviceid. The fixed table would look like:
CREATE TABLE Lastsensordata (
lastSensorNavn varchar(500) UNIQUE NOT NULL,
lastData varchar (500) NOT NULL,
LastTime varchar(50) NOT NULL,
CONSTRAINT PK_Lastsensordata PRIMARY KEY (lastSensorNavn),
CONSTRAINT FK_LastensordataSensordata FOREIGN KEY (lastSensorNavn) REFERENCES Sensordata (ConnectionDeviceId)
);

Related

I want to add more primary key into existing primary key

I wanted to set primary key by combining 3 columns but by mistake i set the key with one column. How should i add other two columns into existing primary keys.
CREATE TABLE facultyQualification(
facultyID CHAR(5) NOT NULL,
level_ VARCHAR(15) NOT NULL,
Exam_Degree VARCHAR(30) NOT NULL,
School_College VARCHAR(50) NOT NULL,
Board_Uni VARCHAR(30) NOT NULL,
year_of_passing DATE NOT NULL,
Max_marks_grades INT NOT NULL,
marks_grade_obtained INT NOT NULL,
perscent_marks INT NOT NULL,
division VARCHAR(10) NOT NULL,
achievement VARCHAR(50),
FOREIGN KEY(facultyID) REFERENCES facultyPersonal(facultyID)
);
SELECT * FROM facultyQualification;
ALTER TABLE facultyQualification
ADD PRIMARY KEY (facultyID);
The primary keys i wanted to make are (facultyID,level_,year_of_passing).
You can do:
alter table facultyQualification drop primary key;
alter table facultyQualification
add primary key (facultyID, level_, year_of_passing);
See example at DB Fiddle.

trying to relate two table together

so pretty new to SQL I created 2 tables which I wanted to be related to one another but I'm getting an error "#1215 - Cannot add foreign key constraint" can someone point me to the right direction of this problem?
CREATE TABLE movie(
id INT(1) NOT NULL AUTO_INCREMENT,
nearname VARCHAR(25) NOT NULL,
release_date DATE NOT NULL,
lang VARCHAR(10) NOT NULL,
PRIMARY KEY(id),
CONSTRAINT same_movie FOREIGN KEY(id) REFERENCES movie_cast(movie_id)
);
CREATE TABLE movie_cast(
movie_id INT(1) NOT NULL AUTO_INCREMENT,
director_name VARCHAR(20) NOT NULL,
actor_name VARCHAR(20) NOT NULL,
actress_name VARCHAR(20) NOT NULL,
PRIMARY KEY(movie_id),
CONSTRAINT same_movie FOREIGN KEY(movie_id) REFERENCES movie(id)
);
You need to refer to the same column name as the primary key. In this case, it is called id:
CONSTRAINT same_movie FOREIGN KEY(movie_id) REFERENCES movie_cast(id)
Of course, your DDL doesn't define movie_cast. So, I am guessing the second table should be something like:
CREATE TABLE movie_cast (
id INT NOT NULL AUTO_INCREMENT,
movie_id int not null,
cast_name varchar(255)
PRIMARY KEY(id),
CONSTRAINT fk_movie_cast_movie FOREIGN KEY(movie_id) REFERENCES movie(movie_id)
);

Mysql foreign key constraint is incorrectly formed?

I am receiving an error when attempting to create some tables in mysql with the foreign key
CREATE TABLE session (
code CHAR(2) NOT NULL,
date DATE,
room VARCHAR(30) NULL,
CONSTRAINT session_pk PRIMARY KEY (date),
CONSTRAINT session_fk FOREIGN KEY (code)
REFERENCES module(code));
CREATE TABLE module (
code CHAR(2) NOT NULL,
name VARCHAR(30) NOT NULL,
cost DECIMAL(8,2) NOT NULL,
credits TINYINT NOT NULL,
course_code CHAR(3) NOT NULL,
CONSTRAINT module_pk PRIMARY KEY (code));
Here are the two tables I am trying to create, the syntax I've used matches w3 schools and both data types are the same so I cannot see how this is incorrect, any help would be appreciated thanks :)
You're trying to create a foreign key on table before creating the referencing table.
Interchanging the order of query will work :
CREATE TABLE module (
`code` CHAR(2) NOT NULL,
name VARCHAR(30) NOT NULL,
cost DECIMAL(8,2) NOT NULL,
credits TINYINT NOT NULL,
course_code CHAR(3) NOT NULL,
CONSTRAINT module_pk PRIMARY KEY (`code`));
CREATE TABLE `session` (
`code` CHAR(2) NOT NULL,
`date` DATE,
room VARCHAR(30) NULL,
CONSTRAINT session_pk PRIMARY KEY (`date`),
CONSTRAINT session_fk FOREIGN KEY (`code`)
REFERENCES module(`code`));
Try this
CREATE TABLE module (
code CHAR(2) NOT NULL,
name VARCHAR(30) NOT NULL,
cost DECIMAL(8,2) NOT NULL,
credits TINYINT NOT NULL,
course_code CHAR(3) NOT NULL,
CONSTRAINT module_pk PRIMARY KEY (code));
CREATE TABLE session (
code CHAR(2) NOT NULL,
date DATE,
room VARCHAR(30) NULL,
CONSTRAINT session_pk PRIMARY KEY (date),
CONSTRAINT session_fk FOREIGN KEY (code)
REFERENCES module(code));

Errno: 1452 Constraint

When I try to source these tables into MySQL, and it created all the tables. Then I start to populate the tables, and it will not let me populate the last table Rental_Invoice. Any suggestions?
The error is
ERROR 1452 (23000): Cannot add or update a child row: a foreign key
constraint fails (SFRC_HIDDEN.Rental_Invoice, CONSTRAINT
Rental_Invoice_fk_Client_Contact FOREIGN KEY (Client_ID)
REFERENCES Client_Contact (Client_ID))
create table Client_Contact
(
Client_ID int Primary Key Auto_Increment,
Client_First_Name varchar(50) Not Null,
Client_Last_Name varchar(50) Not Null,
Client_Address varchar(50),
Client_City varchar(50) Not Null,
Client_State Char(2) Not Null,
Client_Zip_Code varchar(20) Not Null,
Client_Phone varchar(20),
Client_Email varchar(30)
);
create table Owner_Contact
( Owner_ID int Primary Key,
Owner_First_Name varchar(50) Not Null,
Owner_Last_Name varchar(50) Not Null,
Owner_Address varchar(50),
Owner_City varchar(50) Not Null,
Owner_State varchar(2) Not Null,
Owner_Zip_Code varchar(20) Not Null,
Owner_Phone varchar(20),
Owner_Email varchar(30)
);
create table Property_Info
(Property_ID varchar(20) Primary Key,
Owner_ID int Not Null,
Property_Type varchar(30) Not Null,
Pets set('Yes','No') Not Null,
Internet set('yes','No') Not Null,
constraint Property_Info_fk_Owner_Contact
foreign key (Owner_ID)
references Owner_Contact (Owner_ID));
create table Rental_Invoice
( Invoice_ID int Primary Key,
Property_ID varchar(10) Not Null,
Client_ID int Not Null,
Arrival_Date date Not Null,
Departure_Date date Not Null,
Deposit_Amount decimal(5,2) Not Null,
Pet_Deposit_Amount decimal(7,2),
Pet_Type enum('cat', 'dog', ''),
Cleaning_Fee decimal(5,2) Not Null,
Rental_Rate decimal(5,2) Not Null,
Method_Of_Payment varchar(20) Not Null,
constraint Rental_Invoice_fk_Client_Contact foreign key (Client_ID) references Client_Contact (Client_ID)
);
Initial problem
Just a random guess since I don't have MySQL installed anywhere at the moment. But Client_ID in the dependent table is a VARCHAR and it refers to an INTEGER column in the parent table.
After Edit
The foreign key constraint is caused by inserting a row into Rental_Invoice that does not have a corresponding row in Client_Contact. In other words, your data violates the Rental_Invoice_fk_Client_Contact foreign key constraint that requires that Rental_Invoice.Client_ID refers to an existing row in Client_Contact with a matching Client_ID.

Error with creating table

This is my statement, I'm getting an error on Customer_T. The error states:
"01:22:05 DROP TABLE customer_t Error Code: 1051. Unknown table 'energyefficient.customer_t' 0.016 sec"
CREATE TABLE Customer_t
(CustomerID INT NOT NULL,
Name VARCHAR(45) NOT NULL,
Address VARCHAR(256) ,
Email VARCHAR(100) ,
Phone VARCHAR(16) ,
CONSTRAINT PK_CustomerID PRIMARY KEY (CustomerID));
CREATE TABLE Order_t
(OrderID INT NOT NULL,
OrderDate DATE NULL,
CustomerID INT NOT NULL,
CONSTRAINT PK_OrderID PRIMARY KEY (OrderID),
CONSTRAINT FK_CustomerID FOREIGN KEY (CustomerID) REFERENCES customer_t(CustomerID));
CREATE TABLE Equipment
(EquipmentID INT NOT NULL,
EquipmentType VARBINARY(12) ,
YearOfManufacture INT ,
Cost DECIMAL(9,2) ,
Maker VARCHAR(45) ,
Model VARCHAR(45) ,
CustomerID INT ,
CONSTRAINT EquipmentID_PK PRIMARY KEY (EquipmentID),
CONSTRAINT CustomerID_FK FOREIGN KEY (CustomerID) REFERENCES Customer_t(CustomerID));
CREATE TABLE Order_Line_t
(OrderLineID INT NOT NULL,
OrderID INT NOT NULL,
EquipmentID INT NOT NULL,
OrderLineCost DECIMAL(9,2) ,
CONSTRAINT OrderLineID_PK PRIMARY KEY (OrderLineID),
CONSTRAINT OrderID_FK1 FOREIGN KEY (OrderID) REFERENCES Order_t(OrderID),
CONSTRAINT EquipmentID_FK2 FOREIGN KEY (EquipmentID) REFERENCES Equipment_t(EquipmentID));
CREATE TABLE MaintenanceSchedule_t
(MaintenanceID INT NOT NULL,
MaintenanceType VARCHAR(45) NOT NULL,
Schedule_Date DATE NOT NULL,
EquipmentID INT NOT NULL,
ServiceID INT ,
CONSTRAINT MaintenanceID_PK PRIMARY KEY (MaintenanceID),
CONSTRAINT EquipmentID_FK3 FOREIGN KEY (EquipmentID) REFERENCES Equipment(EquipmentID));
CREATE TABLE Service
(ServiceID INT NOT NULL,
EstimatedCost DECIMAL(9,2) NOT NULL,
Status VARCHAR(16) NOT NULL,
ServiceDate DATE ,
EquipmentID INT NOT NULL,
EmployeeID INT NOT NULL,
ActualCost DECIMAL(9,2) ,
ServiceType VARCHAR(45) NOT NULL,
Notes VARCHAR(2000) ,
CONSTRAINT ServiceID_PK PRIMARY KEY (ServiceID),
CONSTRAINT EquipmentID_FK FOREIGN KEY (EquipmentID) REFERENCES Equipment(EquipmentID));
CREATE TABLE Employee_t
(EmployeeID INT NOT NULL,
AnnualSalary DECIMAL(9,2) ,
Name VARCHAR(45) NOT NULL,
DOB DATE ,
POSITION VARCHAR(45) ,
CONSTRAINT EmployeeID_PK PRIMARY KEY (EmployeeID));
try using this:
set foreign_key_checks=0;
drop table energyefficient.customer_t;
set foreign_key_checks=1;
Some time it needs to set foreign key checks to 0;
Thanks
Possibility 1:
Your table creation script does not have any error.
As per the error message shown:
"01:22:05 DROP TABLE customer_t
Error Code: 1051. Unknown table 'energyefficient.customer_t' 0.016 sec"
You are trying to drop the table customer_t in a database named energyefficient.
Possible reason is that you have created the table in some other database and trying to drop from somewhere else.
Possibility 2:
You can modify the drop table to include if exists clause, so that the error is suppressed and ignored silently but with a warning, if such table does not exist.
Example:
DROP TABLE IF EXISTS customer_t;
In case if you are dropping the parent table first, change the global variable foreign_key_checks to false and run the drops.
set foreign_key_checks = 0;
DROP TABLE IF EXISTS customer_t;
-- other drop statements here.
set foreign_key_checks = 1; -- reset to default