Foreign Key hold values of Primay Key - database

I am trying to design a Database for a Patient record.
I am stuck at one point when dealing with Medicine List.
"Table_Patient_Record" - is having a field - "Medicine_Ids" ...
and "Table_Medicine_Record" - having unique - "Id" & "Medicine_Name" ...
Now, my problem is, How to hold multiple(variable) "Id" of "Table_Medicine_Record" into "Medicine_Ids" of "Table_Patient_Record"?
Since, the number of medicines belong to a patient varies from other patients.
Then, how to design database so that from a UI we can Insert, Update and Select.
Thanks, I hope my question is to clear to understand.

If I'm correct, you have a database 'Patients' and 'Medicines'.
The easiest solution is to create a table 'PatientMedicines' that holds a userid and a medicineid.
This way you can connect multiple patients to multiple medicines and the other way around.
And still leaves the freedom that a patient does not need to have any medicine.
Hope this helps.

This seems like a many to many relationship to me. One patient can use multiple medicine, and a medicine can be used by multiple patients. Use a junction table that holds the patient id and the medicine id. Like this:
PatientId | MedicineId
1 1
1 2
2 1
2 3

Related

Storing Entities with User-defined Components in Relational Database

I'm struggling to find the best way to store entities with user-defined fields. I would like to be able to do queries on these fields, so I feel NoSQL may not be the best approach. Constant schema migrations seems like a pain, especially since different users may want different fields on similar entities.
For example, let's say we have an entity representing a village. The village has a name (West Town), a type (village), a population (114). The user may want to add their own attributes to the village, say, a nickname. This is not known up front, and may not be required for other villages.
The best technique I've come up with is a table for the entities, and then a separate table for "components" of the entities, consisting of: a component id, a foreign key to the entity it's on, the name of the component, and its value.
So, the village from the example would exist as:
Table 1 - Entity
ID
1
Table 2 - String Components
ID ENTITY_ID NAME VALUE
1 1 name West Town
2 1 type village
Table 3 - Integer Components
ID ENTITY_ID NAME VALUE
1 1 population 114
Then, if the user wanted to add a "nickname" to the village, they could push a button, select a string component, call it "nickname" and give it a value of "Wesson":
Table 2 - String Components
ID ENTITY_ID NAME VALUE
1 1 name West Town
2 1 type village
3 1 nickname Wesson
Then, when the entity needs to be displayed, we query the component tables for the entity ID, and display the information:
name: West Town
population: 114
type: village
nickname: Wesson
Is this crazy? It feels both sort of like an elegant way to represent a mutable schema in a relational database, and like trying to get around the whole point of a relational database. Is there a better way?
Answering my own question. This seems to generally be addressed using a pattern known as "entity-attribute-value" which is similar to what I've suggested.
The entities table could be a little richer, storing also information common to all entities, like "name" and maybe a foreign key into an "entity_type" table.
At its simplest, the attributes tables could be as above, with one for each data type.
https://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model

design table database, duplicated register or create another table?

I want you to know your opnion about this situation:
I have a table named "movie" with this colums
movie_id
name
price
...... etc
A movie can be available to rent, purchased or both.
If I want a movie available to rent and purchase the price change, for example:
Price for rent: $2.50
Price for purchase: $15.45
The question is:
Is better to make a duplicate in the table movie?
movie_id name price available_for ...... ........
1 300 $2.50 rent
2 300 $15.45 purchase
Or make another table adding the info of price and available_for? Like this:
Table Movie
movie_id name ...... .......... ..........
1 300
2 300
Table Movie_available_for
Id movie_id available_for price
1 1 rent $2.50
2 1 purchase $15.45
I want to know which is the best solution for this
Thanks!
Your relational approach might depend on what level of normalization you hope to achieve. Your question reminds me a lot of the Boyce–Codd normal form (BCNF) vs the 3rd normal form (3NF).
In fact, there is an example similar to your question on this wiki page: Boyce–Codd normal form (Wikipedia)
There is a lot of theory here, but it can many times come down to either what you feel the most comfortable with or whichever technique you can perform the most accurately.
Personally, in this specific case, I would go with the slightly more normalized form (your 2nd example). This is because, the "available_for" and "price" are related variables. If you end up adding more info about movies, that info is potentially going to be duplicated many times. If you add a third "availible_for" or different pricing schemes (1 day for $1.50, 5 days for $4), you will have very significant data duplication.
Besides, when it comes to code, it would be nice to have a movie object that has an array of nested "availible_for" (might name this something else like "offering" or something) objects.
I would suggest you normalize your available_for column as it is repeated and contains few fields only.Store that in another table and create a relation between two tables.
Movie_Available_type
id int, available_for varchar(50)
Then you can use either of two as pointed out by thoughtarray in above post.
I would go with:
Movie (movie_id PK, name, purchase_price, rent_price)
and make the pricing columns nullable. If you don't like nulls, you can decompose it into:
Movie (movie_id PK, name)
PurchasePrice (movie_id PK/FK, price)
RentPrice (movie_id PK/FK, price)

Not allowed to create or change a record in MS Access

I have read numerous thread on the above question, but none of the answers satisfy the problem. My problem is two tables that are linked to each other (in a one to one relationship) using an "ID" field which is also the primary key. When I try to enter a record in the the main table (Don't know if Access knows this is the main table) the I get the following error:
"You cannot add or change a record because a related record is required in table"
Could anyone please help me with this?
Thanks
A "One-To-One" relationship is really a One-To-Zero_or_One relationship, but the table diagrams on the Relationships page in Access do not make it clear which table is the "parent":
However, if you right-click on the line joining the tables and choose "Edit Relationship..." you will see
In this case [Table1] is the "parent" table and [Table2] is the "child" ("Related") table, so we must insert a row into [Table1] before trying to insert the corresponding row into [Table2].
The issue seems to be occuring because you are trying to set the primary key of your table as a foreign table.
What you need to do is create a new column in the 2nd table and link it to the id of the first table, therefore creating a relationship.
Let's take the following simple example since you haven't mentioned the names given to your tables.
In a university environment, you would have the table LECTURER which is linked to the table SUBJECT, so that a lecturer can teach a subject. The relationship between the 2 tables would be so:
LECTURER TABLE
LECTURER_ID | LECTURER_NAME | LECTURER_ADDRESS
SUBJECT TABLE
SUBJECT_ID | SUBJECT_NAME | SUBJECT_DESCRIPTION | SUBJECT_LECTURER_ID
The link between these two tables would be between the SUBJECT_LECTURER_ID from the SUBJECT table and the LECTURER_ID from the LECTURER table. This is a one to one relationship since we are assuming that each subject in this particular university is only taught by one lecturer, and a lecturer can only teach one single subject.
Hope this helps :)

M : N relation ship and table

I have a created a simple db modle for shopping cart lets just consider order , product and shopping cart for now
My question is shopping cart has M:N relation ship with product ? if yes is there a need to create a third table .
I have created third table but it is not making sense for me .I can very well have
T_SHOPPING_CART table and have id ,product_id,quantity as composite primary key and have values of product stored in it rather then creating another table to store these details. Which one is better approach a third table or composite primary key.
I think the answer lies in the fundamentals. You already said that T_SHOPPING_CART and T_PRODUCT have an m:n relationship. So, when you decompose any many to many relationship, it always creates an association table (or gerund).
Let us see why your approach will not work. You want to just use a composite id in the T_SHOPPING_CART table
T_SHOPPING_CART_ID(ID, Product_Id, quantity)
If you include quantity in the primary key, every time a user
changes quantity, your primary key will change. That is not a good
way to design.
What about other attributes you may need? Are you going to add them
as primary key every time? Eg. You need to design a Discount associated with each shopping cart. How will you store it? Can you have a simple m:1 relationship with a table Discount? Since you have a composite key, it will be very inefficient.
Or if you store the Discount as an attribute in the T_SHOPPING_CART table, it will lead to even severe flaw, redundancy. Data redundancy causes all kinds of anomalies.
T_SHOPPING_CART
ID PRODUCT_ID QUANTITY DISCOUNT
1 101 33 2.3
1 102 20 2.3
Here, the Discount for shopping cart with id=1 is 2.3. It is redundant i.e. present at 2 places, which causes update, delete, anomalies.
If you delete a Product, how will you deal with it? If it is Cascade delete, you will lose all the shopping carts which has that product. If you do not cascade, what will you store in place of the deleted item? Null, default value? Very bad design.
My basic argument is if you read the fundamentals of a many to many relationship, you will find all the answers. Many to many should always be linked with a third table.
Hope it helps.

Best way to create a unique number for each many to many relationship

I have a table of Students and a table of Courses that are connected through an intermediate table to create a many-to-many relationship (ie. a student can enroll in multiple courses and a course can have multiple students). The problem is that the client wants a unique student ID per course. For example:
rowid Course Student ID (calculated)
1 A Ben 1
2 A Alex 2
3 A Luis 3
4 B Alex 1
5 B Gail 2
6 B Steve 3
The ID's should be numbered from 1 and a student can have a different ID for different course (Alex for example has ID=2 for course A, but ID=1 for Course B). Once an ID is assigned it is fixed and cannot change. I implemented a solution by ordering on the rowid of the through table "SELECT Student from table WHERE Course=A ORDER BY rowid" and then returning a number based on the order of the results.
The problem with this solution, is that if a student leaves a course (is deleted from the table), the numbers of the other students will change. Can someone recommend a better way? If it matters, I'm using PostgreSQL and Django. Here's what I've thought of:
Creating a column for the ID instead of calculating it. When a new relationship is created assigning an ID based on the max(id)+1 of the students in the course
Adding a column "disabled" and setting it True when a student leaves the course. This would involve changing all my code to make sure that only active students are used
I think the first solution is better, but is there a more "database centric way" where the database can calculate this for me automatically?
If you want to have stable ID's, you certanly need to store them in the table.
You'll need to assign a new sequential ID for every student that joins a course and just delete it if the student leaves, without touching others.
If you have concurrent access to your tables, don't use MAX(id), as two queries can select same MAX(id) before inserting it into the table.
Instead, create a separate table to be used as a sequence, lock each course's row with SELECT FOR UPDATE, then insert the new student's ID and update the row with a new ID in a single transaction, like this:
Courses:
Name NextID
------- ---------
Math 101
Physics 201
Attendants:
Student Course Id
------- ------ ----
Smith Math 99
Jones Math 100
Smith Physics 200
BEGIN TRANSACTION;
SELECT NextID
INTO #NewID
FROM Courses
WHERE Name = 'Math'
FOR UPDATE;
INSERT
INTO Attendants (Student, Course, Id)
VALUES ('Doe', 'Math', #NewID);
UPDATE
Courses
SET NextID = #NewID + 1
WHERE Course = 'Math';
COMMIT;
Your first suggestions seems good: have a last_id field in the course table that you increase by 1 any time you enroll a student in that course.
Creating a column for the ID instead
of calculating it. When a new
relationship is created assigning an
ID based on the max(id)+1 of the
students in the course
That how I'd do it. There is no point of calculating it. And the id's shouldn't change just because someone dropped out.
Adding a column "disabled" and setting
it True when a student leaves the
course.
Yes, that would be a good idea. Another one is creating another table of same structure, where you'll store dropped students. Then of course you'll have to select max(id) from union of these two tables.
I think there are two concepts that you need to help you out here.
Sequences where the database gets the next value for an ID for you automatically
Composite keys where more than one column can be combined to make the primary key of a table.
From a quick google it looks like Django can handle sequences but not composite keys, so you will need to emulate that somehow. However you could equally have two foreign keys and a sequence for the course/student relationship
As for how to handle deletions, it depends on what you need from your app, you may find that a status field would help you as you may want to differentiate between students who left and those that were kicked out, or get statistics on how many students leave different courses.

Resources