mapping table as a reference for another table - sql-server

I have two tables many to many, so i used mapping table for it
1st table: course that contains course_id, course_name, and credit_hrs attributes
2nd table: y_term that contains yt_id, year, and term attributes
mapping table is y_t_course that contains yt_id and course_id attributes
then i create a table, its name is topic, it is contains cpt_id, topic_text.
NOW i used y_t_course as a reference to topic table, it means has foreign key from y_t_course.
my question is how can i represent this relation in ER-Diagram

I would use a tool like Visual Paradigm to get the ER diagrams required. Eclipse also has a plugin that does this.

Related

foreign key or null value to link two long distanced tables

Consider the following database example :
A clinichas many articles
The relationship between supplier and article is many to many ( (1,n) - (1,n))
Let's say I have the clinic's id and I want to retrieve all it's suppliers, what's the best way to do it? is it by creating a "null" article for each supplier in article_supplier OR by creating a foreign key in supplier that references the appropriate clinic?
The latter solution may seem the simplest and easiest but what happens when there is a big chain of tables? Do I keep adding a foreign key each time I need a list of something? e.g :
list of medicines a clinic uses
list of prescriptions a doctor gave
...
If it makes a difference, I am using Laravel's Eloquent ORM
A table represents a relationship among values. (Some values identify entities.) A database can't be used until we are told what each table--base or query result--means: what business/application relationship its rows satisfy. (Ie, what is its (characteristic) predicate.) What are the relationships for your tables?
To query we express a relationship in terms of base relationships then express its table in terms of the corresponding base tables. Eg a join returns rows satisfying one relationship and another. So again, we need to know tables' relationships in business/application terms.
Cardinalities & constraints are properties of relationships given what situations can arise. They aren't needed to update or query. They can guide design & are used for integrity.
When, given a clinic, you talk about "its" suppliers, you do not say what you mean. "Has", "its", "for", "references", "appropriate"--all mean nothing--they refer to related entities, but they don't say how they are related in terms of the business/application. This design contains no explicit relationship on clinics & articles. If it did, you've said nothing by which we could put the right rows in or see the rows & know about the situation. Still, you could then derive clinic-supplier rows where the supplier is "for" some article a given clinic "has". But is that the relationship you mean?? Eg if you want pairs where the clinic is allowed to "have" the supplier "for" some articles, that's a new relationship/table that cannot be derived from what you have.
creating a "null" article for each supplier in article_supplier
That relationship/table is a certain combination of article_supplier & the relationship/table just described. But it is simpler to just have those two.
creating a foreign key in supplier that references the appropriate clinic
That would mean that if a supplier "has" more than one clinic then there can be rows in the new version that differ only by all the other columns; normalization theory says that's worse than the original design and a clinic_supplier relationship/table. And it means that if a supplier "has" no clinic you would need something like a nullable FK (foreign key).
So you likely want a clinic_supplier table. But you should post a new question in which you actually say what business/application relationships you are talking about.
Your question & the following are essentially duplicates in that the basic principles/notions to obviously apply to answer them are all the same:
How do I find relations between tables that are long-distance related?
Required to join 2 tables with their FKs in a 3rd table
Best Solution - Ternary or Binary Relationship
You need to read an information modeling & database design textbook.
In your design :
Supplier is a table.
Articles is a table.
Since Supplier supplies articles, their relationship is expressed in terms of a table that links them. So, there is a supplier_article table.
Clinic is a table.
You mention Clinic uses articles.
By the same principle as above, the relationship between Clinic and Article should be expressed in the form of a table. This should be clinic_article table.
Though you haven't mentioned, you must look at other dependencies that arise. For example, a clinic performs procedures and procedures use articles.
by creating a foreign key in supplier that references the appropriate
clinic
This would assume that one supplier can supply only to one clinic forever. Even if this is true today, it won't be true tomorrow, because you might want to plan for multiple clinics in the same location or using the same application or database.

DataVault modelling for Domain Reference Table

Folks,
Quick Version:
How should I model HUBs, SATs and LINKs when I have multiple domain lookup references in my HUB_SAT?
If you are were to generically model these from the source schema, how would you differentiate between FKs that should be LINKs and FKs that should be References?
Long Version:
I am building out a generic solution for generating DV models from an existing 3NF MSSQL schema. In my source database I have one huge Domain reference table which holds the majority of the business lookup keys
Key INT (Unique)
TypeID INT
Description VARCHAR
Posting Code
... some other fields that are not relevant to the discussion
As I see it there are four basic choices for linking to this table
Create it as a HUB and then produce LINK tables for each business HUB that refers to it
Create it as a single ReferenceLookup table and include the R_ReferenceIDs in the SAT table
Create a separate ReferenceLookup table for each TypeID and link from the SAT using the R_ReferenceID
Create Separate HUBs for each TypeID and generate LINK tables
Create a single LINK table with a LINK_SAT table to hold details of which reference value is mapped by the LINK
and of these #3 feels like the best design (but also the hardest to model correctly - especially as in my case the lookup table has a FK to the Type table)
From the Wikipedia for DataVault,
Reference tables are referenced from Satellites, but never bound with physical foreign keys.
My generic code is based on the design pattern as explained in the BIML DataVault walkthrough
I am looking at all tables in the source schema to determine whether they are a HUB (Have PK and multiple FKs plus fields that are not FKs), SAT (Have PK and only one FK) or LINK (Have PK, more than one FK and all fields are in PK/FK)
I then build:
HUBs with the a HUB_ID and the source PK
SATs with the non FK fields of the HUB source table
SATs for the source SAT tables
LINKs from the source LINK tables
LINKs from the HUB FK relationships
This is all working up to a point (i.e. I have tables for all of the above) however there are some pretty wide tables where a significant number of the fields are simply R_RefID fields all looking up on the same HUB and they are all bound with FKs on the entity table referencing the reference table
E.G. source Asset table has reference fields for
- Asset Type
- Asset Purpose
- Asset Manager
- Asset Funder
- ...
so in the preliminary model I have:
ASSET_HUB (HubID, Asset_ID)
ASSET_SAT (SAT_ID, BuildDate, DisposalDate, ....)
Lookup_HUB (Hub_ID, LookupID)
ASSET_Lookup_1_LINK) (Link_ID,ASSET_HUB_ID,Lookup_HUB_ID)
ASSET_Lookup_2_LINK) (Link_ID,ASSET_HUB_ID,Lookup_HUB_ID)
ASSET_Lookup_3_LINK) (Link_ID,ASSET_HUB_ID,Lookup_HUB_ID)
ASSET_Lookup_4_LINK) (Link_ID,ASSET_HUB_ID,Lookup_HUB_ID)
but there is no way of identifying what each of the LINK tables respresents in the domain model
How would you go about interrogating the schema to determine whether the table is a genuine HUB candidate or whether it should be a REF table instead and how would you determine whether an FK should be treated as a LINK or a SAT.R_RefID. I am after strategy rather than code (but I ;m not going to turn down code if it is on offer :) ) My source DB is SQL2008R2 and my development environment i SQL2016_Dev
In Response to tobi6:
In the source system The business entity has a number of attribute fields which are just XXX_ID types that look up their descriptors from the domain reference table. If you model this domain reference table as a HUB then you either have to have separate link tables for each lookup (LINK tables are automatically generated because there is an FK on the business entity), or multiple active LINK records with a LINK_SAT to identify which attribute you are tracking (actually this creates a 5th design pattern option). If I tag the domain reference table as a REFerence then the XXX_IDs stay in the HUB_SAT which feels like a better solution but is harder to model generically. I.e. how do I determine whether the business entity FK should create a LINK, LINK and LINK_SAT or SAT.R_RefID

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

Personal Protective Equipment Database Structure

I have been asked by my manager to design a Personal Protective Equipment Database for the procurement dept,using SQL Server.In gathering my requirements for the database,I came up with 5 PPE categories:Hands,Eyes & Faces,Head,Body,Footwear.
Currently have one table which stores all the aforementioned categories,
PPCatTable:*
Hands,
Eyes & Faces,
Head,
Body,
Footwear
For each category,there are several has subsets i.e for
Footwear:*
Level of resistance to electric,
HasSteelToe,
Color,
Height,
Gloves:*
Hazard,
Degereeof hazard,
ProtectiveMaterial
but I'm stumped on what the structure of the children's table should be look like,how to store the different subsets for each category.Each subset has different number attributes and procurement dept insists on capturing all the different attributes.
Should I create a table for each child category?
What field should be referenced the child's primary key for the PPEEOrderDetails table?
Should I store the corresponding child attributes as an XML data type in the parent category table?
You want to use the entity supertype / subtype technique to model your items. Consider the following data model:
Your various categories each have their own table, because they have distinct attribute sets. Each sub-category has as its primary key, a column which is also a foreign key to the supertype table: PPEQUIP.
Note that PPEQUIP is not a list of categories, like your PPCatTable. PPEQUIP contains a record for every single item in each of the subtype tables. The columns in PPEQUIP will be the common identifier and a partitioning attribute which is a colum that indicates which subtype applies to the item. If there are other attributes that all types have in common, then those common attributes would also go in PPEQUIP.
Now when you have a table that needs to reference equipment in general, without specific regard to what category the equipment falls into, such as your ORDER_DETAIL then that foreign key reference goes to the supertype table (i.e. PPEQUIP). If on the other hand, you need to reference only a specific category, then you would do that at the subtype level.

Modelling inheritance in a database

For a database assignment I have to model a system for a school. Part of the requirements is to model information for staff, students and parents.
In the UML class diagram I have modelled this as those three classes being subtypes of a person type. This is because they will all require information on, among other things, address data.
My question is: how do I model this in the database (mysql)?
Thoughts so far are as follows:
Create a monolithic person table that contains all the information for each type and will have lots of null values depending on what type is being stored. (I doubt this would go down well with the lecturer unless I argued the case very convincingly).
A person table with three foreign keys which reference the subtypes but two of which will be null - in fact I'm not even sure if that makes sense or is possible?
According to this wikipage about django it's possible to implement the primary key on the subtypes as follows:
"id" integer NOT NULL PRIMARY KEY REFERENCES "supertype" ("id")
Something else I've not thought of...
So for those who have modelled inheritance in a database before; how did you do it? What method do you recommend and why?
Links to articles/blog posts or previous questions are more than welcome.
Thanks for your time!
UPDATE
Alright thanks for the answers everyone. I already had a separate address table so that's not an issue.
Cheers,
Adam
4 tables staff, students, parents and person for the generic stuff.
Staff, students and parents have forign keys that each refer back to Person (not the other way around).
Person has field that identifies what the subclass of this person is (i.e. staff, student or parent).
EDIT:
As pointed out by HLGM, addresses should exist in a seperate table, as any person may have multiple addresses. (However - I'm about to disagree with myself - you may wish to deliberately constrain addresses to one per person, limiting the choices for mailing lists etc).
Well I think all approaches are valid and any lecturer who marks down for shoving it in one table (unless the requirements are specific to say you shouldn't) is removing a viable strategy due to their own personal opinion.
I highly recommend that you check out the documentation on NHibernate as this provides different approaches for performing the above. Which I will now attempt to poorly parrot.
Your options:
1) One table with all the data that has a "delimiter" column. This column states what kind of person the person is. This is viable in simple scenarios and (seriously) high performance where the joins will hurt too much
2) Table per class which will lead to duplication of columns but will avoid joins again, so its simple and a lil faster (although only a lil and indexing mitigates this in most scenarios).
3) "Proper" inheritence. The normalised version. You are almost there but your key is in the wrong place IMO. Your Employee table should contain a PersonId so you can then do:
select employee.id, person.name from employee inner join person on employee.personId = person.personId
To get all the names of employees where name is only specified on the person table.
I would go for #3.
Your goal is to impress a lecturer, not a PM or customer. Academics tend to dislike nulls and might (subconciously) penalise you for using the other methods (which rely on nulls.)
And you don't necessarily need that django extension (PRIMARY KEY ... REFERENCES ...) You could use an ordinary FOREIGN KEY for that.
"So for those who have modelled inheritance in a database before; how did you do it? What method do you recommend and why?
"
Methods 1 and 3 are good. The differences are mostly in what your use cases are.
1) adaptability -- which is easier to change? Several separate tables with FK relations to the parent table.
2) performance -- which requires fewer joins? One single table.
Rats. No design accomplishes both.
Also, there's a third design in addition to your mono-table and FK-to-parent.
Three separate tables with some common columns (usually copy-and-paste of the superclass columns among all subclass tables). This is very flexible and easy to work with. But, it requires a union of the three tables to assemble an overall list.
OO databases go through the same stuff and come up with pretty much the same options.
If the point is to model subclasses in a database, you probably are already thinking along the lines of the solutions I've seen in real OO databases (leaving fields empty).
If not, you might think about creating a system that doesn't use inheritance in this way.
Inheritance should always be used quite sparingly, and this is probably a pretty bad case for it.
A good guideline is to never use inheritance unless you actually have code that does different things to the field of a "Parent" class than to the same field in a "Child" class. If business code in your class doesn't specifically refer to a field, that field absolutely shouldn't cause inheritance.
But again, if you are in school, that may not match what they are trying to teach...
The "correct" answer for the purposes of an assignment is probably #3 :
Person
PersonId Name Address1 Address2 City Country
Student
PersonId StudentId GPA Year ..
Staff
PersonId StaffId Salary ..
Parent
PersonId ParentId ParentType EmergencyContactNumber ..
Where PersonId is always the primary key, and also a foreign key in the last three tables.
I like this approach because it makes it easy to represent the same person having more than one role. A teacher could very well also be a parent, for example.
I suggest five tables
Person
Student
Staff
Parent
Address
WHy - because people can have multiple addesses and people can also have multiple roles and the information you want for staff is different than the information you need to store for parent or student.
Further you may want to store name as last_name, Middle_name, first_name, Name_suffix (like jr.) instead of as just name. Belive me you willwant to be able to search on last_name! Name is not unique, so you will need to make sure you have a unique surrogate primary key.
Please read up about normalization before trying to design a database. Here is a source to start with:
http://www.deeptraining.com/litwin/dbdesign/FundamentalsOfRelationalDatabaseDesign.aspx
Super type Person should be created like this:
CREATE TABLE Person(PersonID int primary key, Name varchar ... etc ...)
All Sub types should be created like this:
CREATE TABLE IF NOT EXISTS Staffs(StaffId INT NOT NULL ,
PRIMARY KEY (StaffId) ,
CONSTRAINT FK_StaffId FOREIGN KEY (StaffId) REFERENCES Person(PersonId)
)
CREATE TABLE IF NOT EXISTS Students(StudentId INT NOT NULL ,
PRIMARY KEY (StudentId) ,
CONSTRAINT FK_StudentId FOREIGN KEY (StudentId) REFERENCES Person(PersonId)
)
CREATE TABLE IF NOT EXISTS Parents(PersonID INT NOT NULL ,
PRIMARY KEY (PersonID ) ,
CONSTRAINT FK_PersonID FOREIGN KEY (PersonID ) REFERENCES Person(PersonId)
)
Foreign key in subtypes staffs,students,parents adds two conditions:
Person row cannot be deleted unless corresponding subtype row will
not be deleted. For e.g. if there is one student entry in students
table referring to Person table, without deleting student entry
person entry cannot be deleted, which is very important. If Student
object is created then without deleting Student object we cannot
delete base Person object.
All base types have foreign key "not null" to make sure each base
type will have base type existing always. For e.g. If you create
Student object you must create Person object first.

Resources