im trying to create a products table with a primary and foreign key with this.
...
here is the code that i have tried so far
CREATE TABLE products
(
prod_id int NOT NULL,
prod_name int NOT NULL,
price varchar(15)
5on_hand varchar(15),
supp_id varchar(20),
PRIMARY KEY (prod_id),
FOREIGN KEY (supp_id)
);
any help would be greatly appreciated
A foreign key is a reference to a field in another table. To specify a foreign key, you have to specify what field(s) it refers to. The database cannot guess this.
So, guessing that supp_id refers to the id in the Suppliers table, your foreign key clause should look like this:
FOREIGN KEY (supp_id) REFERENCES Supplier(id)
I would strongly encourage the following:
All tables have an primary key column that is an integer and auto-incremented.
Names should be character strings.
Prices should be decimals.
So, I'm thinking something like this is appropriate:
CREATE TABLE Products (
ProductId int NOT NULL auto_increment primary key,
Name varchar(255) NOT NULL,
Price decimal(19, 4),
OnHand integer, -- assuming this is quantity on-hand
SupplierId int,
FOREIGN KEY (SupplierId) REFERENCES Suppliers(SupplierId)
);
Related
I have a sport club presence list on paper which I have to bring online.
Basically, I have everything in handle except the SQL schema architecture.
I have never designed a DataBase and I'm not sure if it's the right way. I appreciate any help!
If the person is present we make a x with a pen on paper :)
To do to look the same like on the paper but in an app I try to develop a Java Vaadin App with Spring Data JPA-Hibernate.
On paper and in the future APP look like this:
And this is the MySQL schema:
create table person(
id int PRIMARY KEY AUTO_INCREMENT,
first_name varchar(20)
);
create table isPresent(
id int PRIMARY KEY AUTO_INCREMENT,
isPresent boolean
);
create table persons_isPresent(
person_id int,
isPresent_id int,
FOREIGN KEY (person_id)
REFERENCES person(id),
FOREIGN KEY (isPresent_id)
REFERENCES isPresent(id)
);
create table training(
id int PRIMARY KEY AUTO_INCREMENT,
person_id int,
isPresent_id int,
training_time datetime,
FOREIGN KEY (person_id)
REFERENCES person(id),
FOREIGN KEY (isPresent_id)
REFERENCES isPresent(id)
);
I have never designed a DataBase and I'm not sure if it's the right way. I appreciate any help!
It seems unnecessary to have ispresent ID's.
I would keep your Person table as is.
Create a Training table with an ID and time, and an TrainingAttendance table with a Training ID and a Person ID. If you want to check a person's attendance at a training, check if a record exists in TrainingAttendance with the Person's ID and the Training ID.
CREATE TABLE PERSON (
PERSON_ID INTEGER NOT NULL PRIMARY KEY,
FIRST_NAME VARCHAR(20) NOT NULL);
CREATE TABLE TRAINING (
TRAINING_ID INTEGER NOT NULL PRIMARY KEY
TRAINING_TIME DATETIME NOT NULL);
CREATE TABLE TRAINING_ATTENDANCE (
TRAINING_ID INTEGER NOT NULL,
PERSON_ID INTEGER NOT NULL,
FOREIGN KEY(PERSON_ID) REFERENCES PERSON(PERSON_ID),
FOREIGN KEY(TRAINING_ID) REFERENCES TRAINING(TRAINING_ID),
PRIMARY KEY(TRAINING_ID, PERSON_ID));
I think it might be cleaner to think about training sessions independently. Then you could achieve that with three tables [training]<-[attendee]->[person], where the attendee is a binding table. So maybe something like this:
create table training(
id int PRIMARY KEY AUTO_INCREMENT,
training_time datetime
);
create table person(
id int PRIMARY KEY AUTO_INCREMENT,
first_name varchar(20)
);
create table attendee(
id int PRIMARY KEY AUTO_INCREMENT,
person_id int,
training_id int,
FOREIGN KEY (person_id) REFERENCES person(id),
FOREIGN KEY (training_id) REFERENCES training(id)
);
I tried it out with some simple inserts/select and it might do the trick for you?
insert INTO person (first_name) VALUES ('Pavel');
insert INTO training (training_time) VALUES (NOW());
insert INTO attendee (person_id, training_id) VALUES (1,1);
select person.first_name, training.training_time
from attendee, person, training
where person.id = attendee.person_id
AND training.id = attendee.training_id;
use one_to_many;
create table models(
model_id int primary key auto_increment unique,
name varchar(50),
manufacturer_id int
);
create table manufacturers(
manufacturer_id int primary key,
name varchar(50),
established_on timestamp,
constraint fk_manufacturers_models foreign key(manufacturer_id)
references models(manufacturer_id)
);
When i try to create one to many model like this example https://ibb.co/bPRGQ5 , it throws an error 1215 cannot add foreign key constraint. What am i doing wrong?
models.manufacturer_id must be indexed.
But normally you would put the foreign key constraint on the many table (models) not the one table.
If I understood correctly what you want to get try this
create table manufacturers(
manufacturer_id int primary key auto_increment unique,
name varchar(50),
established_on timestamp
);
create table models(
model_id int primary key auto_increment unique,
name varchar(50),
manufacturer_id int,
foreign key fk_manufacturer(manufacturer_id)
references manufacturers(manufacturer_id)
);
I have multiple tables and they all seem to be fine but there is this one table which I'm trying to create but it wont work because I am keep on getting Error1005 "Foreign key constraint is incorrectly formed".
These are the two tables. I don't know what seems to be the problem.
CREATE TABLE Patient(
ID INT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE,
Name VARCHAR(255) NOT NULL,
Age TINYINT UNSIGNED,
Sex VARCHAR(10),
Contact INT(11),
Email TEXT(2083),
PRIMARY KEY(ID)
);
CREATE TABLE Appointments (
Appointment_No INT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE,
Name VARCHAR(255) NOT NULL,
Contact INT(11),
Date DATE NOT NULL,
Time TIME NOT NULL,
Reason TEXT(2083),
PRIMARY KEY(Appointment_No),
FOREIGN KEY (Name, Contact) REFERENCES Patient (Name, Contact)
);
As per me, table structure should be like below:
CREATE TABLE Patient(
ID INT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE,
Name VARCHAR(255) NOT NULL,
Age TINYINT UNSIGNED,
Sex VARCHAR(10),
Contact INT(11),
Email TEXT(2083),
PRIMARY KEY(ID)
);
CREATE TABLE Appointments (
Appointment_No INT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE,
Patient_ID INT UNSIGNED NOT NULL,
Date DATE NOT NULL,
Time TIME NOT NULL,
Reason TEXT(2083),
PRIMARY KEY(Appointment_No),
FOREIGN KEY (Patient_ID) REFERENCES Patient (ID)
);
FOREIGN KEY (Name, Contact) REFERENCES Patient (Name, Contact)
The referenced columns in the Patient table must be part of a key. Ideally you would want Patient (Name, Contact) to be a unique key, because then the foreign key is guaranteed to reference exactly one row in the Patient table.
But in your table definition, the Name and Contact columns are not part of a key. That explains why you got the error given your table design.
But your table design is not good. Name and Contact are not good choices as a unique key, because two people can share a name, and in theory you could even have two people with the same name with the same contact details (for example, the former boxer George Foreman named his five sons George).
#Shadow is correct that it's a better idea is to reference Patient(id) instead, because it's guaranteed to be unique already.
Define Engine so sql statement would end with
ENGINE = MyISAM;
It should fix the issue.
Try to split the two foreign keys in two lines like this:
FOREIGN KEY (Contact) REFERENCES Patient (Contact)
FOREIGN KEY (Name) REFERENCES Patient (Name)
When trying to create the foreign keys on the last table I get the error "cannot add foreign key constraint" -
create database library_PW;
use library_PW;
create table title(
title_id varchar(20)primary key,
name varchar(50)not null,
reservation_no numeric(10),
lending_time varchar(15));
create table item(
title_id varchar(20)not null,
item_id varchar(20)not null,
constraint pk_item primary key(title_id,item_id));
create table magazine(
mag_id varchar(20)not null,
mag_date varchar(15)not null,
constraint pk_magazine primary key(mag_id,mag_date));
create table book(
ISBN varchar(20)primary key,
date_added date not null);
create table author(
author_id varchar(20)primary key,
author_name varchar(30)not null);
create table book_author(
ISBN varchar(20),
author_id varchar(20),
index (ISBN),
index (author_id),
constraint pk_book_author primary key(ISBN,author_id),
constraint fk_ISBNCode foreign key (ISBN) references book(ISBN),
constraint fk_authorcode foreign key (author_id) references author(author_id));
create table borrower(
membership_id varchar(20)primary key,
name varchar(20)not null,
address varchar(60)not null,
dob date not null,
date_joined date not null,
telephone numeric(12),
email varchar(30));
create table reservation(
title_id varchar(20),
membership_id varchar(20),
reserve_date varchar(20),
index (title_id),
index (membership_id),
constraint pk_reservation primary key(title_id, membership_id,reserve_date),
constraint fk_title foreign key(title_id) references title(title_id),
constraint fk_mem_id foreign key(membership_id) references borrower(membership_id));
create table loan(
title_id varchar(20),
item_id varchar(20),
borrower_date varchar(20),
index (title_id),
index (item_id),
constraint pk_reservation primary key(title_id,item_id,borrower_date),
constraint fk_loantitle foreign key(title_id) references title(title_id),
constraint fk_loanitem foreign key(item_id) references item(item_id));
Thanks in advance!
When I run into this issue, its always because I choose the wrong type data type.. The data type for the child column must match the parent column exactly.
Example: table.key = int & table.child=vchar
For me, its always that! Hope that helps.
Thanks all! It wasn't the data type (for once), it was the problem with the table item as suggested, and SHOW ENGINE INNODB STATUS\G pointed me to the answer.
All that was wrong was in the table item I should have had item_id before title_id.
Thanks again.
I have the following tables (Primary key in bold. Foreign key in Italic)
Customer table
ID---Name---Balance---Account_Name---Account_Type
Account Category table
Account_Type----Balance
Customer Detail table
Account_Name---First_Name----Last_Name---Address
Can I have two foreign keys in the Customer table and how can I implement this in MySQL?
Updated
I am developing a web based accounting system for a final project.
Account Category
Account Type--------------Balance
Assets
Liabilities
Equity
Expenses
Income
Asset
Asset_ID-----Asset Name----Balance----Account Type
Receivable
Receivable_ID-----Receivable Name-------Address--------Tel-----Asset_ID----Account Type
Receivable Account
Transaction_ID----Description----Amount---
Balance----Receivable_ID----Asset_ID---Account Type
I drew the ER(Entity relationship) diagram using a software and when I specify the relationship it automatically added the multiple foreign keys as shown above. Is the design not sound enough?
create table Table1
(
id varchar(2),
name varchar(2),
PRIMARY KEY (id)
)
Create table Table1_Addr
(
addid varchar(2),
Address varchar(2),
PRIMARY KEY (addid)
)
Create table Table1_sal
(
salid varchar(2),`enter code here`
addid varchar(2),
id varchar(2),
PRIMARY KEY (salid),
index(addid),
index(id),
FOREIGN KEY (addid) REFERENCES Table1_Addr(addid),
FOREIGN KEY (id) REFERENCES Table1(id)
)
Yes, MySQL allows this. You can have multiple foreign keys on the same table.
Get more details here FOREIGN KEY Constraints
The foreign keys in your schema (on Account_Name and Account_Type) do not require any special treatment or syntax. Just declare two separate foreign keys on the Customer table. They certainly don't constitute a composite key in any meaningful sense of the word.
There are numerous other problems with this schema, but I'll just point out that it isn't generally a good idea to build a primary key out of multiple unique columns, or columns in which one is functionally dependent on another. It appears that at least one of these cases applies to the ID and Name columns in the Customer table. This allows you to create two rows with the same ID (different name), which I'm guessing you don't want to allow.
Yes, a table have one or many foreign keys and each foreign keys hava a different parent table.
CREATE TABLE User (
user_id INT NOT NULL AUTO_INCREMENT,
userName VARCHAR(100) NOT NULL,
password VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
userImage LONGBLOB NOT NULL,
Favorite VARCHAR(255) NOT NULL,
PRIMARY KEY (user_id)
);
and
CREATE TABLE Event (
EventID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (EventID),
EventName VARCHAR(100) NOT NULL,
EventLocation VARCHAR(100) NOT NULL,
EventPriceRange VARCHAR(100) NOT NULL,
EventDate Date NOT NULL,
EventTime Time NOT NULL,
EventDescription VARCHAR(255) NOT NULL,
EventCategory VARCHAR(255) NOT NULL,
EventImage LONGBLOB NOT NULL,
index(EventID),
FOREIGN KEY (EventID) REFERENCES User(user_id)
);