Referencing multiple rows with one tuple - mysql

First of all, I am a beginner in database area. I'm trying to translate my ER diagram to a database schema. I have a table called research paper and a relationship called citation which references to research paper again. One research paper may have references to many other research papers. Let's say a paper with id=1 citates papers with id=2,3,4,5. How can I accomplish this?

You would accomplish this by creating a junction table (http://en.wikipedia.org/wiki/Many-to-many_(data_model))
In systems analysis, a many-to-many relationship is a type of cardinality that refers to the relationship between two entities (see also entity–relationship model) A and B in which A may contain a parent row[clarify] for which there are many children[clarify] in B and vice versa. For instance, think of A as Authors, and B as Books. An Author can write several Books, and a Book can be written by several Authors. Because most database management systems only support one-to-many relationships, it is necessary to implement such relationships physically via a third junction table (also called cross-reference table),
In this case, since both sides point back to the same table, you'll want to make sure you name the two columns properly so that you can tell which is the research paper, and which are the citations for that paper.
Here's an article with a better representation of the tables (but not as good of an explanation): http://en.wikipedia.org/wiki/Junction_table

Related

Proper data and use of pivot tables

Maybe better as DBA question...
We have a Laravel/MySQL system. We have 4 model types that are also tables, Categories, Stars, Studios and Videos. Contractors set up pivot tables for each of these model types to house multiple many-to-many relationships to each other. The pivot tables are categoryables, studioables and videoables. These each contain the same structure (categoryables as an example):
id, category_id, categoryable_type ('App\Models\Video'), categoryable_id (ID of model type), created_at, updated_at
The current model types we have in each of those pivot tables are:
Categoryables: Star, Studio and Video
Studioables: Star
Videoables: Star, Studio
My questions are:
I know Laravel's pivot table naming convention is normally like category_video, so is appending "able" also a proper naming convention?
Are these even pivot tables, or are they called something else considering they're set up to have multiple data model types, eliminating a simple relationship of just two tables?
What is the best way to house our data for multiple many-to-many relationships? Each model type has a page on our front end, ie. going to a category shows a list of stars, studios and videos. Going to a studio shows a list of categories, stars, and videos, etc. There are 4 possible set ups I can think of:
3a. videoables table is all we use and it has relationships to
stars, studios and videos model types.
3b. We use categoryables, starables and studios only (calling them
category_video, star_video, studio_video) and each of them only has
a relationship to the video model type.
3c. We use all 4 pivot tables and they each contain all of the
relationships to the other 3 model types. This seems like a lot of
bloat and redundancy.
3d. Somewhere in between 3b and 3c. Some sort of perfect combination
of relationships that enhances query speed and performance without
suffering from table bloat and redundant data.
Thanks!
A many-to-many relationship needs an extra "mapping" or "junction" table. ("Pivot" may be used here, but is confusing since it has an unrelated meaning relating to transposing between rows and columns.)
Details on optimal implementation of a Many-to-many table. (I do not know whether Laravel is efficient here.)
Yes, it sometimes makes sense to have a table with 3 ids instead of just 2.
For further discussion, please provide the CREATE TABLEs of one 2- or 3-way relationship table.

E-R model to relational database with one entity twice in one relationship

I am trying as an exercise for an exam to transfer a database from the ER model to a relational database.
However, I am very unsure whether my solution makes sense. In particular, the two relationships between location and has makes great problems. I thought I could add one ZipCode as a regular primary key into the table has and a second ZipCode as foreign key. I would be very grateful if someone could help me with this.
My Solution so far:
If you are following Chen ER design with this Chen ER diagram then you need a table for every entity type box and every relationship (association) type diamond and a FK (foreign key) for every participation/role line for a relationship type.
(It is a bad idea to call lines/FKs "relationships" or "associations" in a Chen context because diamonds/tables represent relationship types and lines/FKs represent participations.)
So your Ship tourID would be dropped in favour of relationship/table takes with lines/FKs to Ship & Tour. And you would have two FKs in the has table to Location. It doesn't matter that you need different column names in the relationship table than in the participant table. A FK just says the values in some table & column list appear in some other table & column list. The diagram says the names are start & target; use them.
Don't use a flaccid uninformative name like has. If you picked a better name and/or explained when a triplet of entities satisfied the has relationship then we could know what reasonable designs would be. Eg you may not be using cardinalities correctly. The Chen way is, a number or range tells for some instance of the entity type how many relationship instances it can participate in. Another way is, a number or range tells you for a some combination of entity instances of the other participating entity types how many instances of the line's entity type can participate with it. If the latter has a zero that means a relationship instance can have a NULL. But that can't arise in a Chen design; participating entity instance combinations identify relationship instances and form PKs (primary keys).
However, a Chen design can't express all relational designs. And we can represent the same data as a Chen ER schema by rearranging tables. Eg dropping binary relationship tables that are not many:many and putting FKs (sometimes nullable) into entity tables instead, just as you did with takes, Ship & Tour. Some methods have non-Chen diagrams expressing such designs directly. Others allow it in the move from Chen diagram to schema. You have to ask your teachers whether they care just what variations from the Chen style of ER diagrams and corresponding schemas you are permitted to make.
(It is this dropping in non-Chen methods of explicit 1:many relationships/associations and their representation by FKs that leads to FKs being incorrectly (but commonly) called "relationships" or "associations".)

Do relationships between tables need to have descriptions?

Do table associations need to have roles. I find this difficult to understand for example if there is a product table and an inventory table and A row in the product table is associated with many rows in an inventory table.(eg. each copy of a particular product has a unique serial number which is a foreign key referencing a column in the inventory table)can be associated with one or (likely) more rows in another table
I find this kind of relationship difficult to describe. If it were inverted you could say a product is held in 1 and only 1 inventory and an inventory contains 1 to many products.
I was having trouble understanding a similar problem as described above until I found the various definitions for the relationships on this page
http://help.filemaker.com/app/answers/detail/a_id/9922/~/understanding-and-creating-many-to-many-relationships-in-filemaker-pro
Maybe I am thinking about it the wrong way
Read about Chen's ERM (Entity-Relationship Model) method/diagrams: Entities are boxes (& entity type tables), relation(ship) types are diamonds (& association tables), participations of entity types are lines from diamond to box (& FKs) and properties (non-entity "participants" or attributes) are ovals on lines. This makes it clear what is a relation(ship)/table and what is a participation/FK. Then some ER variants misuse the term "relationship" for FK and leave out diamonds so it's not so clear what the relation(ship)s and participations are. (See wikipedia Entity-relationship model.) You use the term "role", which is used in Object-Role Modeling for participation (by entity or property). It is the truest to the relational model and can be mapped to ER and ER variant methods. (ER has the problem of artificial distinctions. There is really no difference between an entity, relationship or property, and every table superkey corresponds to an "entity".)

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.

Relational DB Concept

I am trying to lay out the concept for a Relational DB and I ran into some conceptual Problems:
If I have multiple discrete Entities that are "nested" in each other/have a hierarchy e.g.:
Bosses can have multiple Employees. These employees have different Projects they do and One Project has again multiple sections.
So
B1-Bn:
E1-En
P1-Pn
Section1 -SectionN
How would that be best mapped in a database?
Or in other words, how is this hierarchy best mapped in a relational db?
Now I have Costumers that interact with these Employees.
They are met by the bosses
Then they decide which employee will work for them.
Then they are assigned Projects, with one or more sections.
How would that be best mapped.
the Relations 1-n, m-n, 1-1: Can they be used for e.g.:
This is a Foreignkey because of the 1-n relationship.
This is a ManytoManyField because of the m-n relationship.
And is there a excellent online tool to better understand/visualize that.
Thanks so much for your time!
You may want to follow a course on relational database design; this subject takes more than a few days to explain or master. But you are on the right track.
The first thing you may be seeing is a hierarchy, but before you know it there will be relationships that aren't hierarchical, so a network is formed.
This is why relational databases do not work with hierarchies.
You identify different types of entities and have one table for each type.
For each entity type you identify the properties of such entities - each property will be a column of the table.
If a property does not have an atomic value, but a structured value, these structured values must be regarded as an entity, and must be given its own table, and the property will be a foreign key referring that table.
In this way, you will form a network of tables linked by foreign keys. This is called an entity-relationship diagram. Many designers advocate creating such a diagram first, without mapping the entity types to tables directly. They allow many-to-many relationships between entity types in the diagram. A foreign key between tables on the other hand is always many-to-1 or 1-to-1. So these designers have an "implementation" step in which they introduce an additional table for each many-to-many relationship. Personally I don't use many-to-many relationships in my diagrams to begin with.