MySQL create table one to many, what is the best option below? - mysql

I have below data and using mysql. Person_name is unique and TelephoneNumbers are unique per person.
Person_name1=TelephoneNumber1, TelephoneNumber2, TelephoneNumber3...
Person_name2=TelephoneNumber4, TelephoneNumber5, TelephoneNumber6...
Option 1. Create 1:Many master and child table.
CREATE TABLE Person (
personName varchar(50) NOT NULL,
id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id),
UNIQUE KEY personName (personName)
);
CREATE TABLE Telephone (
telephoneNumber int,
mappingId int,
PRIMARY KEY (telephoneNumber),
foreign key(mappingId) references Person(id)
);
Option 2. Create one table with personName, telephoneNumber as Composite Key.
CREATE TABLE
Person_Telephone (
personName varchar(50) NOT NULL,
telephoneNumber int NOT NULL,
PRIMARY KEY(personName, telephoneNumber)
);
Option 1 is it over complicating creating two tables for just two fields?
Option 2 looks perfect and will there be any issues if Option 2 chosen over Option 1?

The option 2 gives you duplicate persons that you must control in every query.
The best is have the entities separate, it's a classic 1-N relation

Since users can have multiple phone numbers, I think 2 tables would be the best solution.
CREATE TABLE person (
PRIMARY KEY (id) AUTO_INCREMENT,
person_name VARCHAR(45) NOT NULL,
);
CREATE TABLE phone_number (
PRIMARY KEY (id) AUTO_INCREMENT,
phone_number VARCHAR(11) NOT NULL,
FOREIGN KEY (person_id) REFERENCES person(id)
)
Now you can simply JOIN the tables like this:
SELECT
t1.id,
t1.person_name,
t2.phone_number
FROM person t1
LEFT JOIN phone_number t2
ON (t1.id = t2.person_id);

Related

Simple attendance list SQL schema architecture advice

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;

Intersection of Two Tables in SQL

Basically I need to create a new table that uses specific information from two other tables.
For example, I have a table called person with the elements person_id, first_name, last_name, gender, age, and fav_quote. I have a second table called department with the elements dept_id, dept_name, and building. I now need to create and intersection table with the person_id and dept_id elements included. And both must be the primary key (which I assume just means PRIMARY KEY (person_id, dept_id) command in my source).
CREATE TABLE person (
person_id INT(8) NOT NULL auto_increment,
first_name VARCHAR(25) NOT NULL,
last_name VARCHAR(25) NOT NULL,
gender VARCHAR(1),
age INT(8),
fav_quote TEXT,
PRIMARY KEY (person_id)
);
CREATE TABLE department (
dept_id INT(8) NOT NULL auto_increment,
dept_name VARCHAR(25) NOT NULL,
building VARCHAR(25) NOT NULL,
PRIMARY KEY (dept_id)
);
That is the code I have for the initial two tables I'm just not sure how to create an intersection and, having gone back over my notes, I can't find the instructions on how to write it.
You got the primary key part right. I'd add foreign keys to your existing table in order to prevent creating interactions with people or departments that don't exist:
CREATE TABLE person_department
person_id INT(8) NOT NULL,
dept_id INT(8) NOT NULL,
PRIMARY KEY(person_id, dept_id),
FOREIGN KEY(person_id) REFERENCES person(person_id),
FOREIGN KEY(dept_id) REFERENCES department(dept_id)
)
You need a table with 2 fields; person_id and dept_id. The table will have foreign keys to the two tables person and department primary keys’ and a composite primary key of both.
Also, this table is only necessary if there is a one to many relationship of person to department. Otherwise just add dept_id as a foreign key in person.

issue with database modelling of many-tom-many [duplicate]

This question already has answers here:
How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?
(4 answers)
Closed 5 years ago.
I want two model 2 simple tables: Account & Manager.
Account can have multiple managers and Manager can have multiple accounts to manage. so we have many-to-many relation between them.
This is how I created them in the db:
CREATE TABLE Account (
accountId int NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
PRIMARY KEY (accountId)
);
CREATE TABLE Manager (
managerId int NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
accountId int NOT NULL,
PRIMARY KEY (managerId),
FOREIGN KEY (accountId) REFERENCES Account (accountId)
);
the problem which is probably obvious to you is that I will have duplicated names and different id's for the same manager, like here:
How would you recommend an sql newbie to do it? :)
I think the way I model it is a one-to-many...
Create a Mapping table ( Egs Account_Manager) to Map Account and Manager and AccountID and ManagerID should be foreign Key.
Regards
Abdul
I would eliminate the accountid/foreign key from manager and introduce a new table to cross reference the two tables. Something like this:
CREATE TABLE ManagerAccount(
id int not null auto_increment,
managerId int not null,
accountId int not null,
primary key(id),
foreign key(managerid) references Manager (ManagerID),
foreign key(accountId) references Account (AccountID)
)
Maybe throw a unique index over the two foreign keys.
Implement a many-to-many relationship with a third table, with foreign keys to the two related tables.
As an example:
person
id
person_name
and
club
id
club_name
A club can have zero, one or more members; a person can be a member of zero, one or more clubs. It's a many-to-many relationship.
The simplest form of the relationship table:
membership
club_id PK, FK ref club.id
person_id PK, FK ref person.id
could be defined ...
CREATE TABLE membership
( club_id INT NOT NULL COMMENT 'PK, FK ref club.id'
, person_id INT NOT NULL COMMENT 'PK, FK ref person.id'
, PRIMARY KEY (club_id, person_id)
, KEY membership_IX1 (person_id)
, CONSTRAINT FK_membership_club FOREIGN KEY (club_id) REFERENCES club (id)
, CONSTRAINT FK_membership_person FOREIGN KEY (person_id) REFERENCES person (id)
)
We note that this relationship itself might have attributes, such as date joined and date resigned. There might also be status (provisional, active, probationary), and we might want to track offices or role within the club.
The relationship might turn out to be more than just a junction or link table. It may actually be an entity in our system. And we probably want to handle it like an entity, adding a separate id column, and also consider removing the requirement that (club_id,person_id) be unique.
Usually, the best way of going about modeling a many-to-many relationship is by creating a separate table to hold it. Using your example:
CREATE TABLE Account (
accountId int NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
PRIMARY KEY (accountId)
);
CREATE TABLE Manager (
managerId int NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
PRIMARY KEY (managerId),
);
CREATE TABLE Account_Manager (
id int NOT NULL AUTO_INCREMENT,
accountId int NOT NULL,
managerId int NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (accountId) REFERENCES Account(accountId)
FOREIGN KEY (managerId) REFERENCES Manager(managerId)
);
This way, any association between a Manager and an Account will be present in the Account_Manager table (e.g. (5,1) would represent patrick's association with the account with accountId = 5). However, to fully understand why this is the most common approach, I'd recommend you read about normalization.

Can a table have two foreign keys?

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

Two or more foreign key in the table

In MySQL I have these 3 tables :
CREATE TABLE IF NOT EXISTS Seasons
(
season_id INT NOT NULL AUTO_INCREMENT,
start_date DATE,
end_date DATE,
club_num INT,
desc TEXT,
PRIMARY KEY(season_id)
);
ALTER TABLE Seasons AUTO_INCREMENT=10000;
CREATE TABLE IF NOT EXISTS Clubs
(
club_id INT NOT NULL AUTO_INCREMENT,
club_name VARCHAR(70),
PRIMARY KEY(club_id)
);
ALTER TABLE Clubs AUTO_INCREMENT=100000;
CREATE TABLE IF NOT EXISTS ClubsCloths
(
season_id INT NOT NULL,
club_id INT NOT NULL,
first_shirt VARCHAR(50),
second_shirt VARCHAR(50),
PRIMARY KEY(season_id,club_id),
FOREIGN KEY (season_id) REFERENCES Seasons(season_id),
FOREIGN KEY (club_id) REFERENCES Clubs(club_id)
);
In the last one I have 2 foreign keys that reference to first and second table. Now I want to know is it wisely to have 2 foreign key in a one table ?
thanks
It is normal. The ClubsCloths table is used to support many-to-many relationship between Seasons and Clubs.
It's perfectly normal to have several foreign keys to different tables (or the same table, doesn't matter).