Intersection of Two Tables in SQL - mysql

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.

Related

passing multiple foregain values in sql cell

I have two tables tb_schools(school_id,school_name), tb_programms(pid,p_name,school_id)
If suppose multiple schools offer the same program then how can I design the DB.
I mean can I pass the list of school_ids like[sc1,sc2,sc3] in school_id of tb_programms.
note: I can't add multiple rows for a single program.
If multiple schools offer the same program you need to design your schema differently. The canonical solution would be to have a table for schools, a table for programs, and a mapping table for the programs held at each school. E.g.:
CREATE TABLE tb_schools (
school_id INT AUTO_INCREMENT PRIMARY KEY,
school_name VARCHAR(30) NOT NULL
);
CREATE TABLE tb_programs (
pid INT AUTO_INCREMENT PRIMARY KEY,
p_name VARCHAR(30) NOT NULL
);
CREATE TABLE tb_school_programs
sid INT NOT NULL,
pid INT NOT NULL,
PRIMARY KEY (sid, pid),
FOREIGN KEY (sid) REFERENCES school(school_id),
FOREIGN KEY (pid) REFERENCES programs(pid)
);

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

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

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't add foreign key to mysql

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)

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