SQL Structure help and query - mysql

I can not find out what is wrong with my SQL Query:
CREATE TABLE Product (
productID int NOT NULL,
name varchar(255) NOT NULL,
price int(255),
PRIMARY KEY (productID)
)
CREATE TABLE User (
userID int NOT NULL,
PRIMARY KEY (userID)
)
CREATE TABLE Purchased (
productID int NOT NULL,
userID varchar(255) NOT NULL,
date date(255), NOT NULL,
FOREIGN KEY (productID) REFERENCES Product(productID) FOREIGN KEY (userID) REFERENCES User(userID)
)
Please can someone help

To start with, you have a syntax error in your third CREATE TABLE statement, where you have specified a comma before NOT NULL constraint and a missing comma before second foreign key definition.
Another thing to note is, you are not supposed to specify any parameter to DATE data type, like you have specified.
EDIT: The data type of userID in this table needs to be same as the data type of the user table for the foreign key to work.
The correct statement is
CREATE TABLE Purchased (productID int NOT NULL,
userID INT NOT NULL,
date date NOT NULL,
FOREIGN KEY (productID) REFERENCES Product(productID),
FOREIGN KEY (userID) REFERENCES User(userID)
)
If you're getting some other error, please update your question

In your query the problem is in date type column so no need to declare the date as variable because it is keyword in sql.
1.Date is a keyword
2.No need to size for date

There are some syntax error in your create table statement.
Date is a keyword so not a good practice to use it.
User_id is int in your USER table and in purchased table you are making it varchar
For date datatype no need to specify the number of characters.
The correct statement is
CREATE TABLE purchased
(
productid INT NOT NULL,
userid INT NOT NULL,
date1 DATE NOT NULL,
FOREIGN KEY (productid) REFERENCES product(productid),
FOREIGN KEY (userid) REFERENCES USER(userid)
)
SQL Fiddle

Use date date NOT NULL
CREATE TABLE Product (productID int NOT NULL, name varchar(255) NOT NULL, price int(255), PRIMARY KEY (productID));
CREATE TABLE User ( userID int NOT NULL, PRIMARY KEY (userID) );
CREATE TABLE Purchased (productID int NOT NULL, userID int NOT NULL , date date NOT NULL,
FOREIGN KEY (productID) REFERENCES Product(productID),
FOREIGN KEY (userID) REFERENCES User(userID))
SQl fiddle

Related

Failed to add the foreign key constraint in MySQL: error 3780

I am getting the error:
Error Code: 3780. Referencing column 'category' and referenced column 'category_id' in foreign key constraint 'product_ibfk_1' are incompatible.
drop table if exists Provider;
drop table if exists Category;
drop table if exists Product;
create table Provider
(
privider_id serial not null primary key,
login_password varchar(20) not null
constraint passrule3 check(login_password sounds like '[A-Za-z0-9]{6,20}'),
fathersname varchar(20) not null,
name_of_contact_face varchar(10) not null,
surname varchar(15),
e_mail varchar(25) unique
constraint emailrule2 check(e_mail sounds like '[A-Za-z0-9]{10,10})\#gmail.com\s?')
);
create table Category
(
title varchar(20),
category_id serial not null primary key
);
create table Product
(
barecode serial not null primary key,
provider_id bigint not null,
manufacturer varchar(25) not null,
category_id bigint not null,
dimensions varchar(10) not null,
amount int not null,
date_of_registration datetime not null,
#constraint 'provider_for_product'
foreign key (provider_id) references Provider (provider_id) on delete restrict on update cascade,
foreign key (category_id) references Category (category_id) on delete restrict on update cascade
);
The datatypes of the two columns referenced in a foreign key constraint need to match
In MySQL, SERIAL is an alias for BIGINT UNSIGNED AUTO_INCREMENT.
To make a foreign key that references this column, it must be BIGINT UNSIGNED, not a signed BIGINT.
You might like to view a checklist of foreign key mistakes I contributed to: https://stackoverflow.com/a/4673775/20860
I also cover foreign key mistakes in more detail in a chapter of my book, SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming.

How to add multiple order rows to given orderid (primary key) in a table

I'm building a small webshop and I have the problem that I can't insert multiple order rows to a specific order due to the primary key constraint. How can I get around this? Out of convenience I would like to have the id autoincremented...
CREATE TABLE order (
id INT NOT NULL AUTO_INCREMENT,
number INT,
productid VARCHAR(15),
customerid INT,
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated TIMESTAMP DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
deleted TIMESTAMP DEFAULT NULL,
ordered TIMESTAMP DEFAULT NULL,
sent TIMESTAMP DEFAULT NULL,
PRIMARY KEY (id),
FOREIGN KEY (productid) REFERENCES product(produktid),
FOREIGN KEY (customerid) REFERENCES customer(id)
) ENGINE INNODB CHARSET utf8 COLLATE utf8_swedish_ci;
You don't put products in the order table. You create another table that has foreign keys to the order and product tables.
CREATE TABLE order_product (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
productid VARCHAR(15),
orderid INT,
quantity INT,
UNIQUE KEY (productid, orderid),
FOREIGN KEY (productid) REFERENCES product(produktid),
FOREIGN KEY (orderid) REFERENCES order(id)
);

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.

Foreign Key Error 1215

Trying to create a foreign key on table Supplier for Supplier_ID referencing table Payment.
CREATE TABLE Payment (
Supplier_ID INT (4) NOT NULL,
Date DATE NOT NULL,
Amount INT (4),
Payment_ID INT (4) NOT NULL,
PRIMARY KEY (Payment_ID, Supplier_ID)
);
Query OK, 0 rows affected (0.10 sec)
CREATE TABLE Supplier (
Supplier_ID INT(4) NOT NULL,
Name VARCHAR(4) NOT NULL,
Country VARCHAR(4) NOT NULL,
Reliability_Score INT(4),
Contact_Info VARCHAR(4),
PRIMARY KEY (Supplier_ID)
FOREIGN KEY (Supplier_ID) REFERENCES Payment(Supplier_ID)
);
ERROR 1215 (HY000): Cannot add foreign key constraint
Please let me know if I can provide additional information, thank you.
A foreign key has to reference a unique column. So the Supplier_ID column needs to be unique.
However, it seems like you might have it backward if I'm understanding your intention correctly. It should probably be a foreign key on supplier_ID in the Payment table referencing the supplier table.
In the context of relational databases, a foreign key is a field (or collection of fields) in one table that uniquely identifies a row of another table. In other words, a foreign key is a column or a combination of columns that is used to establish and enforce a link between the data in two tables.
in your code u have declared primary key as PRIMARY KEY (Payment_ID, Supplier_ID) which is a combination of two columns which is totally fine but while creating foreign key FOREIGN KEY (Supplier_ID) REFERENCES Payment(Supplier_ID) you are referring one column to a combination of two columns which is wrong
read here http://en.wikipedia.org/wiki/Foreign_Key
now your solution:
first create Supplier table
CREATE TABLE Supplier (
Supplier_ID INT(4) NOT NULL,
Name VARCHAR(4) NOT NULL,
Country VARCHAR(4) NOT NULL,
Reliability_Score INT(4),
Contact_Info VARCHAR(4),
PRIMARY KEY (Supplier_ID)
);
now the payment table
CREATE TABLE Payment (
Supplier_ID INT (4) NOT NULL,
Date DATE NOT NULL,
Amount INT (4),
Payment_ID INT (4) NOT NULL,
PRIMARY KEY (Payment_ID, Supplier_ID),
FOREIGN KEY (Supplier_ID) REFERENCES Supplier(Supplier_ID)
);

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