Relational database one to many relation - database

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.

Related

Is there a trigger object I can write to ensure a foreign key, which was left nullable when it was written, is filled in?

I have a database orders table with a foreign key that refers to a customer id in another table. the customer and orders table is a one-to-many relationship. There are several orders in the orders table that do not have a customer id (the foreign key) included in the orders table because the foreign key column was left nullable:
create table orders1
(
orderID int,
customerID int,
customerLName varchar(50),
customerFName varchar(50),
orderTotal float,
primary key (orderID),
foreign key (customerID) references customer1(customerID) -- left nullable
);
I can't go back an fix the entries that have no customer IDs attached, but is there a trigger object I can create that will alert the user if they do not fill in the customer ID value in the future?
No, there is no trigger/code you can write that will be able to guess what customer id a random order should belong to if the insert omits the customer id.
Your best move is to fix the rows that have null customer id and make the FK not nullable.
One reasonable way to fix the rows is to create a dummy customer record and associate the orphaned orders to it. Once that is done, and you alter the column to not null, you will have stopped the rot and can sift through the data to try to figure out what customer those orders actually belong to. You might find the answer in application logs, or perhaps other entities such as payment etc, or maybe the orders are so old nobody cares.

How do I create a relationship between two tables where one already has a relationship with another table?

I am trying to create a Many to Many relationship with SQL Server Management studio between two tables called Courses and Students. This relationship uses a junction table called Enrollment. I started by creating a 1:M relationship between Students and Enrollment so that the studentId column in the Enrollment table points to the studentId column in the Student table. That worked fine. My problem is occurring while I create my 1:M relationship between Courses and Enrollment. The courseId column in the Enrollment table needs to point to the courseId column in the Courses table. The relationship dialogue comes up and the columns under the Primary Key Table(Enrollment are automatically populated with courseId and studentId. The Courses table doesn't have a studentId column, so I remove this from the columns under the primary key table. This is where I get the error message 'The columns in table Enrollment do not match an existing primary key or UNIQUE value. This method worked fine for creating the 1:M between Students and Enrollment. Why am I getting this error all of a sudden?
The reason is your Courses table has 2 field in it's primary key.
On solution is you add a new field named semesterId in Enrollment table and use both semesterId and courseId when creating foreign key.
Your Courses primary key includes a SemesterID which isn't in the Enrollment table. I'd suggest the SemesterID should be in the Enrollments table rather than in the Courses table as a Student would be enrolled in a course in a particular Semester.

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

Change ID of row and reflect this change to all related tables

Old version
I have a Person table and the table Company.
both tables have a column Id (Identity)
Table Company have Ids of 1 to 165
In the table Person have Ids 1 until 2029
New Version
In the new version of the system, was created a table Entity.
This table contains the records of the Companies and People
The Company and Person tables will be maintained, referring to the Entity table.
The Id in table Entity will be the same in Company or Person table
Question
Both tables have multiple relationships with other tables.
Table Entity (as well as others) has a column ID (identity).
The problem is that the Id were repeated when the two tables together (It was to be expected).
How to import without losing relationships?
Attempts
I thought of changing the value of Ids in Company table, starts from 2030.
Thus the Ids would not duplicate when joining the two tables.
But this creates another questions.
How to do this without losing existing relationships?
How to change the Id of a row in the table and this is reflected in all tables which it relates?
I would like to do this using only DDL (SQL Server)
I thought of changing the value of Ids in Company table, starts from 2030. Thus the Ids would not duplicate when joining the two tables.
Create foreign key constraints on the Person table to all related tables (or alter the existing foreign key constraints) with ON UPDATE CASCADE. Then update the Person table and change the values if the id columns - these changes will cascade to the related tables.
To stop further problems, maybe change the identity columns in Person and Company to something like identity( 1000, 3 ) and identity (1001, 3) respectively.
However, I think the best idea is to have a different EntityID column in the Entity table, unrelated to PersonID and CompanyID. The Entity table would also have a column called AltEntityID or BusinessKey that contains the id from the other table and that does not have a unique constraint or a foreign key constraint.
And if you make small modification to your attempt - add new column, say newId, to Company and to Person to manage relation with Entity and leave id columns as is. Why this is the simpliest way? Because new columns shouldnot be identity columns, from one side. From the other side, you can leave all logic of relating other tables with Company and Person intact.

SQL Server table PK and FK

I am creating a relationship between 2 tables:
The relationship I like to form is between the Inventory an InventoryExtended tables.
The primary key for the Inventory table is InvID (Inventory ID).
The reason why I created the InventoryExtended is becauses only 1% of the inventory items in the Inventory table will need additional or extended fields, the rest will not.
Instead of adding these additional fields in the Inventory table where 99% will be blank for 50 additional fields that I need I decided to create an InventoryExtended table and store the 50 fields there.
The relationship between the Inventory an InventoryExtended table will be 1 to 1.
Meaning, for the 1% of the records in the Inventory table , the InvId will be the same as the InvId in the InventoryExtended table.
My question is that should the InvID in the InventoryExtended table be a FK (Foreign Key) or should it be a PK and a FK?
I am thinking it should be a PK and a FK as there the InvID will be unique in the InventoryExtended table.
Thanks in advance.
You are correct.
The InvID should be a PRIMARY KEY and a FOREIGN KEY as it will be unique in the InventoryExtended table.
This type of relationship is indeed 1:1 or (more accurately) 1::0..1, as only some of the rows in the Inventory table will have a related row in InventoryExtended.
Also note that the InventoryExtended (InvID) should not have the IDENTITY property, even if the Inventory (InvID) has it.
The InvID will be both a PK and FK for the extended table.
If you know in advance (meaning when you attempt to fetch data) whether or not a particular inventory type will have the extended data, for such records you can even skip the original table altogether and simply use two disjoint tables smallInventory and bigInventory such that no records of one are present in the other.

Resources