Linking Primary Keys and Foreign keys through a disjointed eer schema - mysql

Hello,
Having a massive difficulty converting a disjointed EER diagram to mysql
I believe the User entity has been setup correctly, just wondering how I would link User to a buyer/seller? Would I add a buyer/seller ID on the user then link that as a FK?
Here is mysql below.. Any help would be greatly appreciated, thanks

Your model shows that the subclasses Buyer and Seller are disjoint specializations of the User entity (A seller cannot be a buyer, and a buyer cannot be a seller) denoted by the circle with 'D'. Depending on your situation, you could challenge this design (can someone sell while having bought in the past?).
Each of these entities have different attributes not common to one another, except the ones shared by a User.
There are different ways of modeling this, but a what you might need for instance, is to have a Buyer table and Seller table. Both of these tables would then contain a foreign key to the User table.
A less normalized alternative is to have a User table that contains attributes from both subclasses, but then some of the attributes would be NULL if they're not applicable. They would then be distinguishable by a Role attribute.
Advised reading: Database Normalization

thanks for all your help, in the end I made buyer and seller tables with the same attributes and then linked them by foreign key back to the USER ID as otherwise I wouldn't have been able to access the attributes..

Related

Relating data from one table to another in mySQL

Here I have a EER diagram I am creating in the MySQL editor.
I want Person to relate to employee. I want some Persons entries to be employees/Customers/etc.
How would I implement this? Would it be a shared key? Join the tables? Related data?
I tried making EmployeeID a foreign key to PersonID. The tables still don't "relate". (There's no way to tell what employee X's name/dob/ect is.)
I encourage you to try again in the direction of making employeeID refer to personID, as a foreign key. You may not have implemented the whole idea.
The technique has a name: Shared Primary Key. If you search on this phrase, you will find articles describing what you have to do when adding a new employee. Without taking the correct steps when a new employee is added, you break the relationship between the two tables.
There is a tag with this name here in StackOverflow. shared-primary-key
What you are basically doing is setting up a situation where employee is a subclass of person. In an object-oriented system, this would be easy. SQL is not object oriented at the base level.

Intermediate SQL Table : What for?

I'm managing to create my first complicated J2E Solution and in every tutorial I find some sort of intermediary tables usage, like here :
Tables : User, User_Roles, Roles
While logic would simply add a key to user Table referring to it's role on Roles table, why the usage of that intermediary table ?
I thought it's one or two developpers choice, but everywhere I look for a tutorial, I find this sort of sql schema.
Is it better ? Does it help in something particular ? Speed, security ? Cause from a logic point of view, using one table User and a foreign key to Roles is better.
Thank you
This is a common database relationship modeling called M-N (Many To Many). A User can have many Roles, and a Role can be assigned to many Users, so you need the intermediary table. Here's another example: a Teacher can teach many Classes, and each Class can be taught by many teachers (during different semesters, for example). In this case you need a Teacher-Class intermediary table.
A different kind of relationship is 1-N (one to N). A User can have many Telephones, but each Telephone is owned by a single User. In this case, a User's primary key (PK) is exported as a foreign key (FK) into the Telephones table. No need for an intermediary table.

How to spot the relationship in RDBMS?

I was studying about relationships in RDBMS.I have understood the basic concept behind mapping relation ship,but I am not able to spot them.
The three possibilities :
one to many(Most common) requires a PK - FK relationsip.Two tables involved
many to many(less common) requires a junction table.Three tables Involved
one to one(very rare). One table involved.
When I begin a project,I am not able to separate the first two conditions and I am not clear in my head.
Examples when I study help for a brief moment,but not when I need to put these principles in to practice.
This is the place where most begineers falter.
How can I spot these relationships.Is there a simpler way?
Don't look at relationships from a technical perspective. Use analogies and real-life examples when trying to envision relationships in your head.
For example, let's say we have a library database.
A library must have books.
M:M
Each Book may have been written by multiple Authors and each Author may have written multiple Books. Thus it is a many-to-many relationship which will reflect into 3 tables in the database.
1:M
Each Book must also have a Publisher, but a Book may only have one Publisher and a Publisher can publish many Books. Thus it is a one-to-many relationship and it reflects with the PublisherId being referenced in the Books table.
A simple analogy like this one explains relationships to their core. When you try to look at them through a technical lens you're only making it harder on yourself. What's actually difficult is applying real world data scenarios when constructing your database.
I think the reason you are not getting the answers that you need is because of the way you are framing the question. Instead of asking “How do I spot the correct type of relationship between entities”, think about “How do my functional needs dictate what relationship to implement”. Database design doesn’t drive the function; it’s the functional needs that drive the relationships you need to implement.
When designing a database structure, you need to identify all the entities. Entities are all the facts that you want to store: lists of things like book titles, invoices, countries, dog species, etc. Then to identify your relationships, you have to consider the types of questions you will want to ask your database. It takes a bit of forward thinking sometimes… just because nobody is asking the question now doesn’t mean that it might not ever be asked. So you can’t ask the universe “what is the relationship between these lists of facts?” because there is no definitive answer. You define the universe… I only want to know answers to these types of questions; therefore I need to use this type of relationship.
Let’s examine an example relation between two common entities: a table of customers and a table of store locations. There is no “correct” way to relate these entities without first defining what you need to know about them. Let’s say you work for a retailer and you want to give a customer a default store designation so they can see products on the website that their local store has in stock. This only requires a one-to-many relationship between a store and the customer. Designing the relationship this way ensures that one store can have many customers as their default and each customer can only have one default store. To implement this relationship is as easy as adding a DefaultStore field to your Customer table as a foreign key that links to the primary key of the Store table.
The same two entities above might have alternate requirements for the relationship definition in a different context. Let’s say that I need to be able to give the customer the opportunity to select a list of favorite stores so that they can query about in stock information about all of them at once. This requires a many-to-many relationship because you want one customer to be able to relate to many stores and each store can also relate to many customers. To implement a many-to-many relationship requires a little more overhead because you will have to create a separate table to define the relationship links, but you get this additional functionality. You might call your relationship table something like CustomerStoreFavorites and would have as its primary key as the combined primary keys from each of the entities: (CustomerID, StoreID). You could also add attributes to the relationship, like possibly a LastOrderDate field to specify the last date that the customer ordered something from a particular store.
You could technically define both types of relationships for the same two entities. As an example: maybe you need to give the customer the option to select a default store, but you also need to be able to record the last date that a customer ordered something from a particular store. You could implement the DefaultStore field on the Customer table with the foreign key to the Store table and also create a relationship table to track all the stores that a customer has ordered from.
If you had some weird situation where every customer had their own store, then you wouldn’t even need to create two tables for your entities because you can fit all the attributes for both the customer and the store into one table.
In short, the way you determine which type of relationship to implement is to ask yourself what questions you will need to ask the database. The way you design it will restrict the relational data you can collect as well as the queries you can ask. If I design a one-to-many relationship from the store to the customer, I won’t be able to ask questions about all the stores that each customer has ordered from unless I can get to that information though other relationships. For example, I could create an entity called "purchases" which has a one-to-many relationship to the customer and store. If each purchase is defined to relate to one customer and one store, now I can query “what stores has this customer ordered from?” In fact with this structure I am able to capture and report on a much richer source of information about all of the customer's purchases at any store. So you also need to consider the context of all the other relationships in your database to decide which relationship to implement between two particular entities.
There is no magic formula, so it just takes practice, experience, and a little creativity. ER Diagrams are a great way to get your design out of your head and onto paper so that you can analyze your design and ensure that you can get the right types of questions answered. There are also a lot of books and resources to learn about database architecture. One good book I learned a lot from was “Database System Concepts” by Abraham Silberschatz and Henry Korth.
Say you have two tables A and B. Consider an entry from A and think of how many entries from B it could possibly be related with at most: only one, or more? Then consider an entry from B and think of how many entries in A it could be related with.
Some examples:
Table A: Mothers, Table B: Children. Each child has only one mother but a mother may have one or more children. Mothers and Children have a one-to-many relationship.
Table A: Doctors, Table B: Patients. Each patient may be visiting one or more doctors and each doctor treats one or more patients. So they have a many-to-many relationship.
An example of one to one:
LicencePlate to Vehicle. One licence plate belongs to one vehicle and one vehicle has one licence plate.

Database for multiple types of users

I've been looking through different questions on here and I can't find something that exactly matches my situation.
I am designing a database for multiple types of users. I have one main User table which includes ID, Username, Password, PasswordSalt, AccountType (enum), and LastLoginDate. I need to have multiple types of accounts: Student, Parent, SchoolAdmin, SystemAdmin, Coordinator, and Teacher. I was originally thinking of having a separate table for each of these types of accounts, but I realized that SchoolAdmin, Coordinator, SystemAdmin, and Teacher all share the exact same data. These account types all have different permissions though. The Student and Parent accounts have extra information that they have to store.
I then thought about adding the information that the 4 identical tables share to the User table and then deleting those tables, but I came across another problem. I need to reference different types of accounts in other tables. For example, I had a foreign key for TeacherID in the Club table to show who the club sponsor is. If I add the information to the User table and get rid of those other tables, then how do I reference a specific account type in another table?
I have never designed a database like this so any help is appreciated.
There are three main ways of implementing inheritance on database models. Please check the links below, and study which is the best one to solve your problem. Nothing better to start analyzing this types of situations to become a good architect.
Single Table Inheritance
Class Table Inheritance
Concrete Table Inheritance
Each of the different approaches have their pros and cons so choose wisely.

Model a table that can have a relationship with several tables

I have a table called 'notes', on this table I need to track who made that note, but the problem is that the creator of the note can be a user stored in one of three possible tables:
users
leads
managers
I have though of simply create three fields on 'notes' to represent the three possible relations: note.user, note.lead, note.manager
With this approach I would be forced to create three table joins when requesting the notes to gather the creators information, and I don't think that is the way to go, so I would like to hear your ideas or comments and what would be the best approach on this.
For me personally this smells like a design problem on a totally different part of the schema: Are manageers not users? Do leads carry person information?
With any approach that creates a relation between one column and one of three others, you will need three joins for the select. If you can't rectify the underlying problem, I recommend you use
note_type ENUM('users','leads','managers')
as an additional field and
SELECT
...
IFNULL(users.name(IFNULL(managers.name,leads.name))) AS name
..
FROM notes
LEFT JOIN users ON notes.note_type='users' AND users.id=notes.note_source
LEFT JOIN managers ON notes.note_type='managers' AND managers.id=notes.note_source
LEFT JOIN leads ON notes.note_type='leads' AND leads.id=notes.note_source
...
for the query
I think you need to abstract out the concept of a user id, so that it does not depend on their role. The author of a note could then be specified by the user id.
Users could be assigned roles, and maybe more than one.
The correct way to structure this would be to pull all common data out of users, leads, and managers. Unify this data into a "contact" table. Then if you want to get all notes for a given manager:
managers->contacts->notes
for a lead:
leads->contacts->notes
Notice your original post: "the problem is that the creator of the note can be a user stored in one of three possible tables"
From the structure of your sentence you even admit that all these entities have something in common; they are all users. Why not make the DB reflect this?
you have to model a parent table for the three tables you already have. Define a table that depicts generally user, leads and manager tables. Something like "Person". So you have all of the ids of the three tables and any common attributes on the Person table. And when you must define the relationship you put the foreign id "Person_ID" on the note table. And when you model user, leads and manager tables you also put the primary key as a foreign key to the Person table.
So you would have something like this:
Table users:
Users(
person_id primary key
...(attributes of Users)
foreign key person_id references Person.person_id
)
This model i depict is common to any relational model you have to model using parents and childs