How connect Two tables that connect the information about Address? - database

I have One table ,reduce the redunduncy i devided into two parts
Table
Email Address(PK)
Name
city
state
Pincode
Country
Land_Line_No
D_O_B
Gender
Marital_Status
After Devided
Table1
Name
city
Land_Line_No
D_O_B
Gender
Marital_Status
Table2
city
state
Pincode
Country
My question is how to connect this two table

An attribute in the second table would be same as the primary key in the first table. These attributes are commonly known as foreign key.
On another issue however, what have you reduced?
You have city in both the tables which looks redundant. Perhaps I am not clear as to what you want.

Schema should look more like this:
Table1 Name municipalityID Land_Line_No D_O_B Gender Marital_Status
Table2 municipalityID city state Pincode Country
Now the municipalityID field in Table2 should be unique on each line thus making it the primary key of the table. In order to associate any record form Table with a specific city, etc.. you would reference the proper municipalityID (this is a foreign key in Table1 referencing Table2).

Related

Postgres index performance with duplicated data

Having a table with the following columns:
users
id | name | city
--------+---------+-----------
As many users are in the same city the same city could appear many times. By adding an index on it, do we get a performance benefit as values are repeated? or would it negatively affect performance?
Query I'm trying to run
SELECT DISTINCT city FROM users;
The real solution here IMHO, is to normalize that table and create a new City table. Like this:
User
idUser: Primary key
Name
City_idCity <-- foreign key to the City table
City
idCity: Primary key
Name
This way, there is no index to maintain (idCity is a primary key to table City anyway). To get a list of existing cities, just
SELECT Name FROM City
Thus you do not need DISTINCT and avoid a full table scan.
You will also get the other benefits of normalized tables.
Ex. is the city of New-York the same as New York? Or NewYork? This ensures users will always have 1 single choice of city, and not create duplicates like they would do in a free text field.

Handling multi-select list in database design

I'm creating a clinic management system where I need to store Medical History for a patient. The user can select multiple history conditions for a single patient, however, each clinic has its own fixed set of Medical History fields.
For example:
Clinic 1:
DiseaseOne
DiseaseTwo
DiseaseThree
Clinic 2:
DiseaseFour
DiseaseFive
DiseaseSize
For my Patient visit in a specific Clinic , the user should be able to check 1 or more Diseases for the patient's medical history based on the clinic type.
I thought of two ways of storing the Medical History data:
First Option:
Add the fields to the corresponding clinic Patient Visit Record:
PatientClinic1VisitRecord:
PatientClinic1VisitRecordId
VisitDate
MedHist_DiseaseOne
MedHist_DiseaseTwo
MedHist_DisearThree
And fill up each MedHist field with the value "True/False" based on the user input.
Second Option:
Have a single MedicalHistory Table that holds all Clinics Medical History detail as well as another table to hold the Patient's medical history in its corresponding visit.
MedicalHistory
ClinicId
MedicalHistoryFieldId
MedicalHistoryFieldName
MedicalHistoryPatientClinicVisit
VisitId
MedicalHistoryFieldId
MedicalHistoryFieldValue
I'm not sure if these approaches are good practices, is a third approach that could be better to use ?
If you only interested on the diseases the person had, then storing the false / non-existing diseases is quite pointless. Not really knowing all the details doesn't help getting the best solution, but I would probably create something like this:
Person:
PersonID
Name
Address
Clinic:
ClinicID
Name
Address
Disease:
DiseaseID
Name
MedicalHistory:
HistoryID (identity, primary key)
PersonID
ClinicID
VisitDate (either date or datetime2 field depending what you need)
DiseaseID
Details, Notes etc
I created this table because my assumption was that people have most likely only 1 disease on 1 visit, so in case there's sometimes several, more rows can be added, instead of creating separate table for the visit, which makes queries most complex.
If you need to track also situation where a disease was checked but result was negative, then new status field is needed for the history table.
If you need to limit which diseases can be entered by which clinic, you'll need separate table for that too.
Create a set of relational tables to get a robust and flexible system, enabling the clinics to add an arbitrary number of diseases, patients, and visits. Also, constructing queries for various group-by criteria will become easier for you.
Build a set of 4 tables plus a Many-to-Many (M2M) "linking" table as given below. The first 3 tables will be less-frequently updated tables. On each visit of a patient to a clinic, add 1 row to the [Visits] table, containing the full detail of the visit EXCEPT disease information. Add 1 row to the M2M [MedicalHistory] table for EACH disease for which the patient will be consulting on that visit.
On a side note - consider using Table-Valued Parameters for passing a number of rows (1 row per disease being consulted) from your front-end program to the SQL Server stored procedure.
Table [Clinics]
ClinicId Primary Key
ClinicName
-more columns -
Table [Diseases]
DiseaseId Primary Key
ClinicId Foreign Key into the [Clinics] table
DiseaseName
- more columns -
Table [Patients]
PatientId Primary Key
ClinicId Foreign Key into the [Clinics] table
PatientName
-more columns -
Table [Visits]
VisitId Primary Key
VisitDate
DoctorId Foreign Key into another table called [Doctor]
BillingAmount
- more columns -
And finally the M2M table: [MedicalHistory]. (Important - All the FK fields should be combined together to form the PK of this table.)
ClinicId Foreign Key into the [Clinics] table
DiseaseId Foreign Key into the [Diseases] table
PatientId Foreign Key into the [Patients] table
VisitId Foreign Key into the [Visits] table

Relational database one to many relation

I am using Access to create a database. I have two tables with the following data.
Car
CarID - PK
CarName
CarPrice
CustomerID
Customers
CustomerID -PK
Username
Password
CarID
I wish to have the relationship as many cars to one customer. Would I need a 3rd 'link' table or is there a way to do this without another table? Sorry for such a simple question
Remove CarID from your Customer table. Make CustomerID in the Car table a foreign key to Customer, and remove any existing unique constraints on that column.
Remove CarID from your customers table and you would be set. Just be sure to have the CustomerID field in the Car table be a Foreign Key.

Update Foreign Key when copying records to a different table

I have two tables which I want to merge together. They both have the same columns. However, the records I want to copy over are referenced by another table.
As a result, when I update the reference to the new table, the references are no longer correct. How should I go about updating the references so that they remain correct?
EDIT - Apologies - a little more detail:
At the moment I have this:
INSERT INTO Suppliers
(Name, Reference, Telephone, Email, ContactName, AddressId, CommentSetId)
SELECT Name, Reference, Telephone, Email, ContactName, AddressId, CommentSetId
FROM Hotels
I want to delete the table "Hotels" but need to make sure the reference from another table "HotelContract" is still correct after copying the records to the table "Suppliers"
EDIT 2 - This is SQL server 2005.
I have a table "HotelContract" which has the Foreign Key "HotelId". I have updated this to "SupplierId", to be used when the hotels have been copied to the "Supplier" table.
If you have another unique key in Hotels and Suppliers (e.g. Name) you can use this key to update SupplierId in HotelContract (drop foreign key constraint to Hotels first). You can do this with a join between HotelContracts, Hotels and Suppliers:
update HotelContract
set SupplierId = S.SupplierId
from HotelContract C
inner join
Hotels H
on H.HotelId = C.SupplierId -- assuming the pk column in Hotels is HotelId
inner join
Suppliers S
on S.Name = H.Name -- assuming Name is unique in both tables
If you don't have such a unique key you have to store the original HotelId (now SupplierId) from Hotels within a temporary column in Supplier. The update of HotelContract is simple in this case.
Restore foreign key of HotelContract afterwards.

Linking ID from one table to data in another table

I have an assignment where I am to create two tables within a database. The tables looks like this;
ContactPerson (ID, Forename, Surname, Email, PhoneNumber)
Company (ID, CompanyName)
Now my problem is that I have to link a ContactPerson to a specific company, but I can't have them in the same table.
I understand that I can use the join statement to show both tables in one query but I need the database to know which person is linked to which company when I implement this databse into my asp.net project.
How do I do this?
You did say "specific" company so I'm assuming you have one company per person.
Put a column in the user table called CompanyID...
ALTER TABLE ContactPerson
ADD CompanyID int
(assuming your ids are ints)
and then create the following foreign key:
ALTER TABLE [dbo].ContactPerson
ADD CONSTRAINT [FK_ContactPerson_Company]
FOREIGN KEY (CompanyID)
REFERENCES Company (ID)
Shark is correct if you want a many to many relationship.
To get all people in a company:
SELECT
*
FROM
ContactPerson
WHERE
CompanyID = x
You don't HAVE to apply the foreign key constraint, but if you don't, you can accidentally put invalid data in. All a "Constraint" does is enforce a rule for you, in other words "making sure sql knows which people are in which company" as your question suggests you need to do.
The above query would work without the Foreign key constraint, but then your database doesn't "know" about the relationship.
..and if I try and insert a person with a companyid that doesn't exist, SQL will throw an error (this is a good thing).
Since this is a one-to-many relationship, I would typically put that data into the ContactPerson table. But because you explicitly say you cannot, then just create a join table:
create table ContactPersonCompany
(
ContactPersonID int not null foreign key references ContactPerson(ID),
CompanyID int not null foreign key references Company(ID)
)
Now you have a relationship between ContactPerson and Company.
Example: select all people from a particular company
select
cp.Surname,
cp.Forename
from ContactPerson cp
inner join ContactPersonCompany cpc
on cp.ID = cpc.ContactPersonID
inner join Company c
on cpc.CompanyID = c.ID
where c.CompanyName = 'Some Company'

Resources