sql Error 1064 (42000) Syntax Error - mysql

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

Related

MySQL Error "Can't create table" Foreign Key Constraint

I'm trying to create a database using MySQL and having difficulties with my code. I created the base table with one attribute that I plan on using as a foreign key in another table but an error message comes up saying I cannot create the table. I only want help with creating that table as I know how to insert data.
create database aerogames_table;
CREATE TABLE
O_DETAILS
(
B_Number INT NOT NULL,
B_Name VARCHAR(60) NOT NULL,
Order_ID INT NOT NULL,
Order_CName VARCHAR(50) NOT NULL
)
engine=innodb;
CREATE TABLE
P_DETAILS
(
PRO_ID INT NOT NULL PRIMARY KEY,
Order_ID INT NOT NULL,
CONSTRAINT fk_OrdID_this FOREIGN KEY (Order_ID) REFERENCES O_DETAILS(Order_ID),
PRO_Seller VARCHAR (50) NOT NULL,
PRO_Name VARCHAR (50) NOT NULL,
PRO_Year INT NOT NULL,
PRO_Price INT NOT NULL
)
engine=innodb;
1005 - Can't create table 'aerogames_table.p_details' (errno: 150)
Due to this https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html
[CONSTRAINT [symbol]]
FOREIGN KEY [index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
Foreign key need to reference to index column (no need to be primary key) so you need to create index on O_DETAILS.Order_ID like this
CREATE TABLE
O_DETAILS
(
B_Number INT NOT NULL,
B_Name VARCHAR(60) NOT NULL,
Order_ID INT NOT NULL,
Order_CName VARCHAR(50) NOT NULL,
KEY (Order_ID)
)
engine=innodb;
CREATE TABLE
P_DETAILS
(
PRO_ID INT NOT NULL PRIMARY KEY,
Order_ID INT NOT NULL,
CONSTRAINT fk_OrdID_this FOREIGN KEY (Order_ID) REFERENCES O_DETAILS(Order_ID),
PRO_Seller VARCHAR (50) NOT NULL,
PRO_Name VARCHAR (50) NOT NULL,
PRO_Year INT NOT NULL,
PRO_Price INT NOT NULL
)
engine=innodb;
Certainly if you make O_DETAILS.Order_ID to be primary key, it will also create for you and this works

errno 150 mySQL foreign key

This SQL is giving me Errno 150 when i'm trying to create the second table with the foreign key on UserID
Can anyone please advice me what am i doing wrong?
CREATE DATABASE IF NOT EXISTS OTA;
USE OTA;
CREATE TABLE IF NOT EXISTS Users
(
UserID int AUTO_INCREMENT NOT NULL PRIMARY KEY,
UserName varchar(255) NOT NULL,
Email varchar(255) UNIQUE ,
PW varchar(255),
PN varchar(255),
Admin BIT
);
CREATE TABLE IF NOT EXISTS Notes
(
UID int AUTO_INCREMENT NOT NULL PRIMARY KEY,
Note varchar (255) NOT NULL,
c_Date Date NOT NULL,
c_text varchar (255) NOT NULL,
FOREIGN KEY (UID) REFERENCES Persons(UserID)
);
Sorry for being a duplicate question but i can't find my answer between the related ones.
The problem is that you are trying to reference Persons(UserID) when your first table is called Users. Try this for your key:
FOREIGN KEY (UID) REFERENCES Users(UserID)
However, you should have a separate column for the note ID.
Try declaring the primary key after:
CREATE TABLE Orders
(O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id))
Also, you auto-incremented both UID and UserID. This is fine if they are the same length, but if you try to reference a foreign key value that doesn't exist, you will get an error.

Creating MySQL relationships with foreign keys and alter statements

I will try to be specific because I feel my understanding of the subject isn't quite precise as well. My problem is understanding how to create relations between tables with foreign keys which I add with alter statements. I have these tables.
CREATE TABLE article (
content TEXT NOT NULL,
published_on DATE NOT NULL,
created_on DATE NOT NULL,
);
CREATE TABLE category(
name VARCHAR(30) NOT NULL,
date_created DATE NOT NULL,
);
CREATE TABLE user(
income FLOAT(30, 30) NOT NULL,
password VARCHAR(30) NOT NULL,
picture_url TEXT NOT NULL,
);
CREATE TABLE tag(
description VARCHAR(30) NOT NULL,
second_priority FLOAT(30, 30) NOT NULL,
);
To which I have to make there relationships:
Tag has a one to one connection to Category
Category has a many to one connection to User
User has a one to many connection to Article
And to do that I use there statements:
ALTER TABLE tag ADD CONSTRAINT FOREIGN KEY (tag_id) REFERENCES category (category_id);
ALTER TABLE category ADD CONSTRAINT FOREIGN KEY (user_id) REFERENCES user (user_id);
ALTER TABLE user ADD CONSTRAINT FOREIGN KEY (user_id) REFERENCES article (user_id);
My problem is that the third one fails. When I switch the places of article and user the constraint passes. After a bit of digging and experimenting I found out that I can't constraint two keys from which one is either UNIQUE or PRIMARY KEY and the other one just NOT NULL. So far I don't know how to continue, can someone please enlighten me as to how to create a one to one, many to one, one to many and a many to many relationship between these tables because I am kinda lost and everything in my head is a mess.
FULL STUFF:
CREATE DATABASE exam_database;
USE exam_database;
CREATE TABLE article (
content TEXT NOT NULL,
published_on DATE NOT NULL,
created_on DATE NOT NULL,
user_id INT(30) NOT NULL
);
CREATE TABLE category(
name VARCHAR(30) NOT NULL,
date_created DATE NOT NULL,
category_id INT(30) NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE,
user_id INT(30) NOT NULL
);
CREATE TABLE user(
income FLOAT(30, 30) NOT NULL,
password VARCHAR(30) NOT NULL,
picture_url TEXT NOT NULL,
user_id INT(30) NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE
);
CREATE TABLE tag(
description VARCHAR(30) NOT NULL,
second_priority FLOAT(30, 30) NOT NULL,
tag_id INT(30) NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE
);
ALTER TABLE tag ADD CONSTRAINT FOREIGN KEY (tag_id) REFERENCES category (category_id);
ALTER TABLE category ADD CONSTRAINT FOREIGN KEY (user_id) REFERENCES user (user_id);
ALTER TABLE user ADD CONSTRAINT FOREIGN KEY (user_id) REFERENCES article (user_id);
First Your structure has some errors:
Missing PK, Why using INT(30)? etc...
Your DB should looks like:
CREATE DATABASE exam_database;
USE exam_database;
CREATE TABLE article (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE,
user_id INT NOT NULL,
content TEXT NOT NULL,
published_on DATE NOT NULL,
created_on DATE NOT NULL
);
CREATE TABLE category(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE,
user_id INT NOT NULL,
name VARCHAR(30) NOT NULL,
date_created DATE NOT NULL
);
CREATE TABLE user (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE ,
income FLOAT(30, 30) NOT NULL,
password VARCHAR(30) NOT NULL,
picture_url TEXT NOT NULL
);
CREATE TABLE tag (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT UNIQUE,
category_id INT NOT NULL,
description VARCHAR(30) NOT NULL,
second_priority FLOAT(30, 30) NOT NULL
);
Second Your FKs should look like:
ALTER TABLE tag ADD CONSTRAINT FOREIGN KEY (category_id) REFERENCES category (id);
ALTER TABLE category ADD CONSTRAINT FOREIGN KEY (user_id) REFERENCES user (id);
ALTER TABLE article ADD CONSTRAINT FOREIGN KEY (user_id) REFERENCES user (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

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 ;