Relationship between database tables - sql-server

I have an existing DB schema like this.Is there a way to create any kind of referential integrity between these two tables. What exactly is the kind of relationship ? Is it many to many with just two classes
Student table:
ID Name CourseID
------------------------
1 Student1 100023
2 Student2 100023
3 Student3 100024
4 Student4 NULL
Course table:
ID CourseID CourseName
--------------------------
1 100023 Course1
2 100022 Course2
3 100024 Course3
4 100023 Course6
ID is the primary key in both the tables. CourseID is the column for the relationships.

Definitely. You can create a Foreign Key constraint between Student.CourseID and Course.CourseID. You can either do it through SQL Server Management studio directly or by using an ALTER TABLE/ADD CONSTRAINT statement. Personally, I find the Management Studio easiest to use.
Do a search on "SQL Foreign Key Constraints" and you should find a W3Schools (or something similar) explaining everything you need to know to get started with them.

Looking the table you have described and assuming CourseID would be unique in Course table it is many to one/zero relation between Student and Course
or can be said zero/one to many relation between Course and Student table.
but I feel this is not a good design it should have three tbales
Course table
Student table
Bridge table for Course and Student

Related

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

many to many normalization

I'm studying Database normalization and I just can't understand one thing.
Suppose we have a Many-to-Many relation. We have a table Course and we have a table Student. Multiple students may take multiple courses.
Suppose we have a "transition" table Course_Student that stores only primary keys of a student and a course he has chosen.
My task is to make all tables in 3NF and if some table is not in 3NF then to explain why.
My question is: are these tables already in 3NF and I'm especially concerned about the "transition" table.
Thanks so much!
Course
id title
1 Math
2 Programming
Student
id name
1 John Stevens
2 Jack Ryan
Course_Student
course_id student_id
1 1
1 2
2 1
CREATE TABLE Course(
id int IDENTITY(1,1) PRIMARY KEY,
title varchar(100) NOT NULL
)
CREATE TABLE Student(
id int IDENTITY(1,1) PRIMARY KEY,
name varchar(50) NOT NULL
)
CREATE TABLE Course_Student(
course_id int FOREIGN KEY REFERENCES Course,
student_id int FOREIGN KEY REFERENCES Student
)
As per my understanding of Normalization, your tables are already in 3.5 NF (BCNF). The design of your table is great.
Over normalization can be bad sometimes but in your case it seems perfectly sane.
For the Table (Course_Student)
Primary Key should be (course_id, student_id)
with 2 foreign keys, referencing the two table :) !
Assessing normal form is something that is done to a database design that includes, for each table, the applicable functional dependencies.
Absent an explicit statement of the latter, all dependencies can only be assumed to be on (all) the keys, and hence the design can only be assumed to satisfy (at least) BCNF, by definition.

Microsoft Access 2013 - Multiple Foreign Keys in the same Record

I’ve encountered a problem with pulling multiple foreign keys into one record in a Microsoft Access table.
I’ve got two tables with these fields:
Table 1:
Owners
Fields:
Owner ID (Primary Key)
First Name
Last Name
Table 2:
Ships
Fields:
Ship ID (Primary Key)
Ship Name
I need to create a relationship between Table 1 and Table 2 which shows who owns the ship. I’ve tried adding a number field to Table 2 called Owner ID (Foreign Key) and this works absolutely fine.
Working Example:
Table 1 – Owners Table 2 – Ships
Owner ID (Primary Key)__ Ship ID (Primary Key)
First Name \ Ship Name
Last Name \________Owner ID (Foreign Key)
Unfortunately my ships in Table 2 can have multiple owners (up to 5) at the same time. My problem arises when I try to create a series of linking fields in Table 2.
Not Working:
Table 1 – Owners Table 2 – Ships
Owner ID (Primary Key)__ Ship ID (Primary Key)
First Name \ Ship Name
Last Name \ Owner1 ID (Foreign Key)
\______/ Owner2 ID (Foreign Key)
\ Owner3 ID (Foreign Key)
Can anyone recommend any workarounds so I can show multiple owners taken from the Owners table in the Ships table?
Thanks for your help!
Your database design is definitely incorrect.
In the case you explain, you have a many-to-many relationship between Ships and Owners, which MUST translate into a "relationship table" in the relational model.
In this case: a [Ownership] table, with 2 fields, being the 2 Primary Keys (PK) of the related tables.
In other words, you need 3 tables:
Ships(ShipId, ShipName, Whatever) PK is ShipId
Owner(OwnerId, FirstName, LastName) PK is OwnerId
OwnerShip(ShipId, OwnerId) PK is made of the 2 FKs
The problem is that it looks like Access doesn't allow Nullable FK's and so all Owner fields would have to be filled in, no matter how many owners there are.
The only solution to this I can think of is to introduce a ShipOwner table, which has ShipID and OwnerID columns (as FK's to the Ship and Owner tables). You can then have as many Owners as you like.
Pros: You can add things like %Owned if that matters
Cons: The software has to enforce the limit of 5 owners
Biggest Pro: it will work!
Cheers -
EDIT: The first para is wrong: Access does let you add nullable FK's. However I still thing the suggestion here is a good one. Repeating Groups (Owner 1 to 5) is against Normalisation rules, and this suggestion is normalised.

Database problem--student registering for the same class twice..how to stop it Access 20007

I am making a mock database and I have a student table, student_class linking table, and a class table. How can I make it so that a student cannot be registered for the same class twice?
Example: StudentID 21 and classID 34 can be entered X number of times in the linking table.
The tables are designed 3NF, too.
In your student_class linking table (otherwise called a composite table), make both values, StudentID and ClassID, primary keys. So that table will have 2 columns that are composite primary keys and also foreign keys to their associated tables. Does that make sense?
A student_class table probably has at least two columns. One would be a foreign key to the primary key in student; the other would be a foreign key to the primary key in class. You need a primary key constraint on that pair of columns.
For example, if student_class had the two columns student_id and class_id . . .
Open the table student_class in design view.
Select both those columns.
Click the key icon.
That should do it.
You could have a table that tells you which students are enrolled in which classes, named students_classes. If you make a composite primary key on this table containing student_id and class_id, then it should be impossible to have the database contain a student in the same class twice.
I should point out that you should not have an auto-increment ID primary key column on this table (I think Access likes to add this by default so if it did you may have to remove it). If you do, you could still end up with duplicates if all three are a part of the key. Example:
ID student_id class_id
113 1 2
114 1 2
Having the ID field still allows you have a student enrolled twice in the same class.

Resources