Error with creating table - mysql

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

Related

Trigger for last inserted value

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

Cannot add foreign key constraint in MySQL

MySQL:
CREATE SCHEMA IF NOT EXISTS otes_db;
USE otes_db;
CREATE TABLE IF NOT EXISTS school(
school_code CHAR(3),
school_desc VARCHAR(255) NOT NULL,
school_head INT UNSIGNED NOT NULL,
PRIMARY KEY(school_code),
FOREIGN KEY(school_head) REFERENCES user(user_id)
ON DELETE CASCADE
ON UPDATE CASCADE
)ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS user(
user_id INT UNSIGNED,
user_lname VARCHAR(255) NOT NULL,
user_fname VARCHAR(255) NOT NULL,
user_mname VARCHAR(255),
user_email VARCHAR(255) UNIQUE NOT NULL,
user_password VARCHAR(255) NOT NULL,
user_type ENUM('CEO', 'VP', 'HEAD', 'CHAIR', 'STUD') NOT NULL,
user_isActivated ENUM('Y', 'N') DEFAULT 'N',
PRIMARY KEY(user_id)
);
Based on this thread, I have checked for the following:
InnoDB Engine is set in school table
The referenced key is a primary key (user_id)
The data types are the same (INT UNSIGNED)
However, I'm still getting the error with the school_head and user_id. Anything I missed?
You need to create the user table first

SQL error: #1005 - Can't create table

Here is my code:
create table if not exists Pelajar (
no_pelajar char(7) not null,
nama varchar(30) not null,
alamat varchar(50) not null,
no_telepon varchar(10),
grade integer not null,
primary key (no_pelajar)
);
create table if not exists Kelas (
kode_kelas char(5) not null,
no_pengajar char(9) not null,
no_pelajaran char(4) not null,
ruang integer not null,
waktu char(5) not null,
primary key (kode_kelas)
);
create table if not exists Pelajaran (
no_pelajaran char(4) not null,
grade integer not null,
subjek varchar(30) not null,
primary key (no_pelajaran)
);
create table if not exists Pengajar (
no_pengajar char(9) not null,
nama varchar(30) not null,
alamat varchar(50) not null,
no_telepon varchar(10) not null,
primary key (no_pengajar)
);
create table if not exists Pembayaran (
no_pembayaran char(11) not null,
status_pembayaran varchar(11) not null,
tgl_pembayaran char(8) not null,
primary key (no_pembayaran)
);
create table if not exists KartuAnggota (
no_pelajar char(7) not null,
kode_kelas char(5) not null
);
create table if not exists SlipPembayaran (
no_pembayaran char(11) not null,
no_pelajar char(7) not null
);
alter table SlipPembayaran
add foreign key (no_pembayaran)
references Pembayaran(no_pembayaran);
alter table SlipPembayaran
add foreign key (no_pelajar)
references Pelajar(no_pelajar);
alter table KartuAnggota
add foreign key (kode_kelas)
references Kelas(kode_kelas);
alter table KartuAnggota
add foreign key (no_pelajar)
references Pelajar(no_pelajar);
alter table Kelas
add foreign key (no_pelajaran)
references Pelajaran(no_pelajaran);
alter table Kelas
add foreign key (no_pengajar)
references Pengajar(no_pengajar);
=================================================================================
after running the code, i got the message:
SQL query:
ALTER TABLE KartuAnggota ADD FOREIGN KEY ( kode_kelas ) REFERENCES Kelas( kode_kelas ) ;
MySQL said:
#1005 - Can't create table 'bimbel.#sql-2f2c_1c6' (errno: 150)
can you explain that?
If you re-create a table that was dropped, it must have a definition that conforms to the foreign key constraints referencing it. It must have the right column names and types, and it must have indexes on the referenced keys, as stated earlier. If these are not satisfied, MySQL returns error number 1005 and refers to error 150 in the error message.

sql Error 1064 (42000) Syntax Error

CREATE TABLE IF NOT EXISTS message(
id INT NOT NULL auto_increment,
userid INT NOT NULL,
date Date NOT NULL,
text varchar(255) NOT NULL,
PRIMARY KEY ('id')
FOREIGN KEY ('userid') REFERENCES users('id'));
I was just wondering if someone could help me in identifying a syntax error as I can not create a table.
Try to put , after the primary key declaration.
Update: I guess it should be
CREATE TABLE IF NOT EXISTS message (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
userid INT NOT NULL,
date Date NOT NULL,
text varchar(255) NOT NULL,
FOREIGN KEY (userid) REFERENCES users(id));
I'm assuming this is for MS SQL Server? If you get MS SQL Server Studio, you can script stuff which gives you an idea:
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[message]') AND type in (N'U'))
CREATE TABLE message(
id INT IDENTITY NOT NULL,
userid INT NOT NULL,
date Date NOT NULL,
text varchar(255) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (userid) REFERENCES users(id))
GO
You query should be as below
CREATE TABLE IF NOT EXISTS message (
id INT auto_increment PRIMARY KEY,
userid INT NOT NULL,
date Date NOT NULL,
text varchar(255) NOT NULL,
FOREIGN KEY (userid) REFERENCES users(id));
Provided you have id as a primary key in users table.
CREATE TABLE users (id INT PRIMARY KEY)
Your query should look like this:
CREATE TABLE IF NOT EXISTS message(
id INT NOT NULL auto_increment,
userid INT NOT NULL,
date Date NOT NULL,
text varchar(255) NOT NULL,
PRIMARY KEY ('id'),
FOREIGN KEY ('userid') REFERENCES users('id')
) Engine=InnoDB;
Note the , after PRIMARY KEY ('id').
Small trick
You don't have to specify foreign keys in table definitions. It's practical when you do it like this (because dump may export tables in order that foreign keys will fail on creating/inserting):
CREATE TABLE 1; -- With references to table 2
CREATE TABLE 2;
INSERT INTO 1;
INSERT INTO 2;
ALTER TABLE 1 ADD FOREIGN KEY (user_id) REFERENCES 2 2(id);
Try to change the name of your table, May be message is an in-built keyword in MySQL.
Update to this: I guess it should be
CREATE TABLE IF NOT EXISTS myMessage (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
userid INT NOT NULL,
date Date NOT NULL,
text varchar(255) NOT NULL,
FOREIGN KEY (userid) REFERENCES users(id));

MYSQL, When defining a table does the UNIQUE constraint have to be used in conjunction with an INTEGER or can it be any datatype?

I am wanting to have a label column (VARCHAR) and I want it to be unique, but when I try to create the table it seems to be throwing an error. Can a unique constraint only be used in conjunction with an INTEGER or will it work with other datatypes as well. The error I am getting is (ERRNO 150)
CREATE TABLE IF NOT EXISTS `user`(
user_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
`password` VARCHAR(255) NOT NULL
);
CREATE TABLE IF NOT EXISTS `element`(
element_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
label VARCHAR(5) NOT NULL DEFAULT '',
parent_id INT NULL,
user_id INT NOT NULL,
created_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
edited_on TIMESTAMP NOT NULL,
UNIQUE(label),
KEY element_1 (label),
CONSTRAINT FK_element_1 FOREIGN KEY (user_id) REFERENCES `user` (user_id),
CONSTRAINT FK_element_2 FOREIGN KEY (parent_id) REFERENCES `element` (element_id)
);
The only way I can have this error, if the first table is created with MyISAM engine and the second (tried to be created) with InnoDB.
Check the definition of the created table user, using:
SHOW CREATE TABLE user ;
If that's the case, drop it and recreate it with:
CREATE TABLE IF NOT EXISTS `user`(
user_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
`password` VARCHAR(255) NOT NULL
)
ENGINE = InnoDB ;