Modelling a two-way relationship using one row with MySQL - mysql

Let's say that I have a MySQL table that I wish to use to use to model a relationship between two entities (A and B, for example). There are three columns: Person1, Person2, and Relationship. Let's further say that A and B are persons in this table and could have one of several relationship types, such as being friends, one requesting the other to be a friend, and so forth.
Is it possible (and preferable?) to use one row to do this? It seems like having one row that represents the A->B part of the relationship and another for the B->A part of the relationship would be a somewhat fragile setup, since if either of the two ever neglects to be updated the model could be in a rather odd state (A thinks B is a friend, B thinks A is something else).
The other part of my question is: how would efficient look-ups work? If there was only one row to represent the relationship, wouldn't all queries need to do a SELECT to check whether it is in the Person1 field or the Person2 field? Is there a nicer way of modelling this type of data?
(I realize this explanation is a little rough; please let me know if you'd like any clarification.)

You could have a column for the person who requested the relationship, the "requestee", the type of relationship (friend, etc), and whether the relationship has been approved by the "requestee"

Related

Supplier-customer relationship in the same table

I'm no MySQL expert and I have to design a rather complex db for my level.
The problem I'm facing now consist in having a supplier-customer relationship within the same table (macro categories of companies):
Macro table
id name mega_id macro_customer_id
------------------------------------------
1 Furniture 2 2,4,5,35
I want to represent the fact that macro entry with id 1 has other macro companies (which are their customers) described within the same table.
Which is the best way to represent this?
Thanks!
It depends: We all used to use the normalization forms (as #1000111 indicated), however depending on the use of the data, you can choose to look different at certain parts of this normalization discussion:
The normal model for this would be:
Table userData(id,name)
- 1:N table linkTable(id,macro_customer_id)
- N:1 table metaData(macro_customer_id,value)
Or:
Table userData(id,name)
- 1:N table linkTable(macro_customer_id,id)
The big question is however in how the data is used. If data is just for this user and not queried in any other way (no where, or group by), then storing it as a serialized String is a completely valid approach.
The relationship between entities in an RDBMS should be stored in a relational way. Ask yourself if you care about this relationship in your database - will you need to write queries that will link macro.id to table/rows represented by IDs in macro.macro_customer_id? If yes, then you must store this relationship in a (one-to-many or many-to-many) separate table.

Mysql xref table- add column or sparate

I have a cross reference table that contains three major columns:
object id
different object id
relation type between the two
Problem is, on some cases I need two more columns that help define the relation between the two objects.
My question is, what is the proper way to deal with the situation?
Should I create another table with five columns, and have two table for practically the same purpose?
Or is it ok to add two more columns that will almost always contain null. Will it needlessly affect response time and size?
Thanks
edit-
I've been asked for more information, so here it is:
the database hold philosophical arguments.
This specific table holds the information of which which statements are connected in what logic.
these are the columns:
statement_id
logic_id
direction
which are good for two-way logic (such as 'if-then');
But in case of a multiple statement logic (such as 'and' or 'or') I needs two more columns:
exit
inner-logic type
I'm not sure if this extra information helpful or just more confusing. feel free to ignore it and answer the question on purely academic base.
It is ok to have two ids and any number of columns describing the relationship. Those extra columns could be NULLable if they are optional or whatever.
It sounds like the two ids JOIN to a single table, correct? In that case, you may need to UNION two selects to check for an id in either of the columns. And have multiple indexes, one starting with one id, one starting with the other.
It would help if you provided SHOW CREATE TABLE and a SELECT or two. That might give us a better feel for what the tables are for.

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.

What is the Best Practice for Composite Key with JPA?

I am creating a DB for my project and I am facing a doubt regarding best practice.
My concrete case is:
I have a table that stores the floors of a building called "floor"
I have a second table that stores the buildings called "building"
I have a third table that stores the relationship between them, called building_x_floor
The problem is this 3rd table.
What should I do?
Have only two columns, one holding a FK to the PK of building and another holding an FK to the PK of floor;
Have the two columns above and a third column with a PK and control consistency with trigger, forbidding to insert a replicated touple of (idbuilding, idfloor)?
My first thought was to use the first option, but I googling around and talking I heard that it is not always the best option.
So I am asking for guidance.
I am Using MySQL 5.6.17
You don't need third table. Because there is one-to-many relationship between building and floor.
So one building has many floors and a floor belongs to one building. Don't get things complicated. Even though you need a table with composite keys, you should be careful. You need to override equals and hashCode methods.
I am still not confortable with that approach. I am not saying it is wrong or innapropriate, very far from that. I am trying to understand how the informations would be organized and how performatic it would be.
If I have a 1:* relationship, like a student may be attending to more than one subject along its university course within a semester I would Have the 3rd table with (semester, idstudent, iddiscipline).
If I try to get rid of the join table my relationship would be made with a FK inside student table or inside subject table. And it does not make sense to do that because student table is a table for a set of information related with registering the info of a person while the discipline table holds the data of a discipline, like content, hours...it is more a parametric table.
So I would need a table for the join.

MySQL foreign key connecting to two tables with a constant?

We have a MySQL database with employees, companies and addresses tables.
The setup works like this: employees and companies each have an id. Since they are in two different tables, an employee can have id = 1 and the company can have id = 1. Both can have multiple addresses.
Now the address table has two columns that links it either to a company or to a employee:
element_id
element_type_id
element_type_id is either 1 = person or 2 = company
The whole thing is a bit more complex and there are many more tables, but that kinda explains the concept.
The problem is now that we would like to start using the Entity Framework and for that we need to define relationships with foreign keys.
But that sounds pretty much impossible with the setup that we currently have, does it?
Since the address table would need to be combined with the person and the company somewhow....
Any ideas?
This concept is known as polymorphic associations. I once asked a question about it, because I had a similar data structure that I wanted to make referentially sound. In terms of this question your Address corresponds with the Comment table and Employee and Company with Person etc.
The answer was excellent. If you can change the schema I would certainly go for it and use that approach.
If you can't change the schema you can always subtype your Address class in your EF model and use element_type_id as the discriminator column. You would create subtypes EmployeeAddress and CompanyAddress, where Employee refers to the former and Company to the latter. But as "the whole thing is a bit more complex" I'm not sure if this will be feasible in your situation.
You already meantioned yourself that this concept is not fitting into a relational database. It is not wrong, MySQL and all the other just don't support it. And it is not a normalized layout, so it might be regarded bad practice by database engineers.
You should think about separating the address from the relation by creating two additional tables: employee_adresses and company_addresses, each holding a relation to the company and the address or the employee and the address. This way you might get one address that is used for a company and many employees, which might be a good thing (normalized structure).