Relationship between database tables - database

I've got a question relating databases which i can't find the anwser for myself. Currently i got a situation where i have a database with two tables. The two tables are named items and items_sequences. What i want to do is make a relationship between the primary key of the item database and a field in the items_sequences table. Below an illustrated example.
| Items | | items_sequences |
|-------| |------------------|
| id | | sequence_id |
| foo | | counter |
The point is creating the relationship isnt hard. But what i want to do if an Item is made an item sequence should be also made containing a sequence_id with the primary key of the Item itself. And if a Item is deleted the item_sequence should be deleted as well. By the way this should be a 1:1 relationship.
I forgot how this can be done, i would really appreciate if someone would point me to the right direction. Currently i am using a postgresql database if it matters.
Thanks,
Antek

If I get this right, you want to look into using foreign keys and triggers.

If it's a 1:1 relationship, could you not just combine the tables?

Related

Complex Database Design: columns or data

For an existing database we are considering to improve part of the database design.
25 tables have very similar structures, about 90% identical columns & data types. And fairly frequent changes to the tables, for example we may need to add 2 new columns to 7 of these 25 tables. A few months later the 2 new columns may be required in 5 further tables, etc. We also get questions like how many rows in these tables have IsActive (see example below) = TRUE. This currently means creating 25 SQL statements and the statements are much more complex than this simple example. It just feels wrong to query 25 tables and then combine the results.
One option we discussed would be to store all data in a master table. However in total this would mean having quite a wide table and quite a lot of NULL values.
A further idea we discussed is to keep the 25 tables and create a master view, which combines these tables. The view would however need a lot of manuall maintenance and the update could get forgotten & the view would still work.
In database design one of the main concepts is: "For maximum flexibility, data is stored in columns, not in column names.", which leads us to the main question. Does anyone have experience in storing columns in a table? The columns actually contain filter criteria for business logic.
Here is an example:
Table 1: Business Rule 1
CustomerID (int) | IsPremiumCust (bool) | HasCreditCard (bool) | IsActive (bool) | OrderThreshold (int)
Table 2: Business Rule 2
CustomerID (int) | IsPremiumCust (bool) | HasCreditCard (bool) | IsActive (bool) | Discount (int)
further 23 tables like these. All with more columns than in this examples.
Suggestion: Criteria table
Criteria ID | Criteria | Data Type
1 | IsPremiumCust | bool
2 | HasCreditCard | bool
3 | IsActive | bool
4 | OrderThreshold | int
5 | Discount | int
Suggestion: Business Rule table
Business Rule ID | Name
1 | Business Rule 1
2 | Business Rule 2
Suggestion: Intersection table
CustomerID | Business Rule ID | Criteria ID | Criteria Value
------------------------------------------------------------
1 | 1 | 1 | TRUE
2 | 2 | 1 | FALSE
I know this doesn't really work, as the Criteria Value field could have different data types. However I hope someone might have had a similar situation and can think of a full solution for this question.
This would allow us to add criteria without having to keep changing many table structures.
It sounds like you should have one table that has the core fields from your 25 common tables, with an additional field for the type of record that corresponds to the current existing table names. Then, you want one or a few supplemental tables that use the primary key for you new core table and also store just the additional fields needed by each type of record. If you find yourself with a new set of columns that only apply to a handful of existing tables, that's fine. You only need records for those records from the core table in your new supplemental table. And when those columns expand to include more of your original tables, adding records to the supplemental table is easy. You can still build a master view from this, if you need it.
I think reply to you question is good property inheritance tree for end entity. If tree will be optimized for problem domain you will be have efficient database scheme without null values. Problem with quantity of sql statements you can close by suitable ORM.

EAV database design for model with multiple attributes (other models)

I have a model that possesses a lot of attributes with multiple values that are either representations of lists or other models. My research led me to consider an Entity-Attribute-Value design to represent such but I have seen more discouragement from more knowledgeable people than recommendations.
One that sticks to me is this comment:
In a nutshell, EAV is useful when your list of attributes is frequently growing, or when it's so large that most rows would be filled with mostly NULLs if you made every attribute a column. It becomes an anti-pattern when used outside of that context.
by Karl Bielefeldt.
Basically my model is student_report. It has the following attributes based on the actual form:
id
creator
revision history
department
references
funding (optional, variable/not fixed)
comments
objectives (paragraph)
scope (paragraph)
creator, revision history, department, references, funding and comments are other models that this form will rely on.
My initial plan is to create student_report with only the following:
id
id of creator
objectives
other paragraph-style content
while the others: revision history, department, references, funding and comments will posses the foreign key student_report_id.
For the variable/not fixed models such as references and funding, I plan to use a mediator table to connect student_form to the "list" of those to normalize the DB:
student_report
| id | name |
|----|-----------------|
| 1 | Abraham Smith |
| 2 | Betty Gladstone |
| 3 | Chen Hong |
references
| id | name |
|----|--------------|
| 1 | Reference 1 |
| 2 | Reference 2 |
| 10 | Reference 10 |
report_references
| user_id | reference_id |
|---------|--------------|
| 1 | 2 |
| 1 | 3 |
| 2 | 10 |
Is my proposed solution enough? This will be a small-scale project and I doubt this will require hundreds of use a day.
EAV helps you capture data when the data model is not well understood. It allows you to skip over data analysis and to come up with a single design that is so adaptable that it will handle a body of data no matter what the actual structure of the data is.
But there's a downside. Since you haven't analyzed the data at storage time, you have to analyze the data when you go to retrieve it and turn it into something useful, such as a report or an extract. Otherwise your results are meaningless. This downside can, in some circumstances be much larger than the upside you experienced earlier.
In your case, you seem to have a good understanding of the attributes you want to store, and the semantics of those attributes. It also looks unlikely that the attribute list is going to have to expand based on surprises.
So I advise you to avoid EAV, and instead concentrate on how to compose relations out of attributes. Relations are simply collections of attributes, grouped together in some way that is meangful and useful. You can read books about this topic, if you care to.
In SQL, tables represent relations. Tables have rows, that represent tuples. Tables have columns, that represent attributes. The intersection of a row and a table provides a location where a value can be stored. In !NF, each location stores a "simple" value.
Your design looks pretty good to me. I think it will serve you better than an EAV model would. I don't know whether it's completely normalized, and I'm not sure it has to be.

How to differentiate a many-to-many relationships while designing a database?

I have to design a database. And I am finding entities and their relationships. But every relationships seems to have a many-to-many relationships. For instance, in my case:
1) A staff manages client
Here a staff can manage zero or more client. Similarly, a client is managed by one or more client.
2) A client orders to buy a stock
Here a client can order zero, one or more stock to buy and a stock can be ordered by zero, one or more client.
3) A client orders to sell a stock
Here a client can order zero, one or more stock to sell and a stock can be ordered by zero, one or more client to sell.
These are some of the examples of my situation. And I am confused how to separate these relationships. There are other numerous cases like these in my scenario. And I am having difficulty to conceptualize the design.
SO, please enlighten me regarding my situation.
It seems like there's quite a lot to the system you are developing and presumably there are requirements you haven't mentioned so it isn't really possible to come up with a complete answer. But hopefully some of the following will help you to "conceptualize the design" as you describe it.
1) This is a very common scenario and there's pretty much a standard way of dealing with these many-to-many relationships.
If there are 2 entities A and B with a many-to-many relationship then you would normally introduce an entity C that consists of 2 columns - one a foreign key to the unique id of A and the other a foreign key to the unique id of B. And you would remove the foreign key column in entity A pointing to B and vice versa.
i.e
|-----|
| A |
|-----|
\|/
|
|
/|\
|-----|
| B |
|-----|
becomes:
|-----| |-----|
| A | | B |
|-----| |-----|
| |
| |
| |
/|\ /|\
|-------------|
| C |
|-------------|
The main challenge is often what to call these new entities! Sometimes they might just be something like a_b_relationship but it's good if can identify more meaningful names.
2) It looks like you need to do a bit more analysis to identify all the actual entities. One way of doing this is to go through your description of the system and identify the nouns - often if there's a noun in the description it's appropriate to have an entity in the entity-relationship diagram.
"Order" jumps out as a noun you overlooked.
Typically for order-processing you would have 2 entities - the order that contains the date, total value, customer etc, and a child orderline which identifies how many of which product have been ordered and individual prices. So in ecommerce a shopping cart would be the order and each item in the shopping cart would be an orderline record.
In your scenario we'd have:
|----------| |-----------|
| client | | product |
|----------| |-----------|
| |
| |
| |
/|\ /|\
|-------------| /|-------------|
| order |--------| orderline |
|-------------| \|-------------|
3) Client sells many products
Here you are identifying an additional role for a client and what I'd do here is question whether "client" is an appropriate entity at this stage. You may find it easier to think in terms of "buyer" and "seller" until the first-cut design is understood. If buyer and seller have a lot in common (especially if an individual can be both a buyer and a seller) then you may decide to use a single entity eventually. Your ERD tool may provide support for this - have a search for "subtype entities" or "entity subtypes".
The specifics will depend on your actual application but it could be that each orderline should have a relationship to the seller, and the order a relationship to the buyer. This will depend on whether it is possible for example for a buyer to order a number of items of a particular product, some of which are sourced from one seller and some from another. It could get complicated!
Also, it might be helpful to consider whether you need to record a seller's stock prior to it being sold. Here it might be useful to distinguish between "product" and "stock", e.g.
|---------| |-----------|
| seller | | product |
|---------| |-----------|
| |
| |
| |
/|\ /|\
|-----------------|
| stock |
|-----------------|
As a general comment I'd say it really can help to go through the design process step by step. So once you have got your initial model, assign all the data items you need to store to the appropriate entity, and methodically make sure that the design is in first normal form, then second normal form then 3rd normal form. Only once you have done this, and are confident that the design reflects the requirements, should you think about how to implement the design in a database. That's what I learned many years ago anyway!
That's hard to answer this question. Everything in designing is situational. If you really need to store which of staffs manage the client and a client could managed by many staffs, yes your relation is many-to-many. Pay attention there is many relations between entities in real world; you should just store which of them are important and necessary to be stored.
For another example, if your stock contain the available count of that kind of goods, thus the relation between client and stock is many-to-many too.
Note: Don't use plural form of noun for you tables' name, it leads you to be confused about relations.
Edit: To apply many-to-many relationship in your database tables, you will need a mediator table. For example about Customer and Product table, you should create a table named CustomerProduct (Or everything you want). CustomerProduct table contains two foreign keys, one from Customer table and another from Product table. Usually (not all the time) one many-to-many relationship breakdown to two many-to-one relationships.
See this Link .

Database structure and relationships

I'm building this gaming portal and I have some database concerns. Currently I have about 10 tables, but I think they will be more than 20 when I'm finished programming. Anyway, I want to create some sort of relationships between the different tables (somewhat like WordPress). That table will hold any relation that one row from table A has to a row in table B. And what I came up with is the following:
table relationships
| rs_id | rs_type | rs_alpha | rs_beta |
rs_id -> just an id
rs_type -> the type of relation
rs_alpha -> related table #1 and row id
rs_beta -> related table #2 and row id
examples:
| 1 | cover | games:153 | images:318 |
| 2 | tag | news:183 | tags:18 |
| 3 | group_admin | users:918 | group:75 |
...
This might just do it, but here it comes my concerns:
1. This table is going to grow so fast that in no time there might be over 100,000 rows which will slow the load time.
2. To extract info I'll have to explode every call which might slow down the load time.
3. I might divide table name from id (rs_alpha, rs_beta), yet that might also slow down the load time.
Thank you and I'm open to any other solutions that might be better than this one :)
If you have time you can download my db structure from here to see what it looks like:
demirevdesign.com/public/pcanvil.sql.gz
(The addon_ tables will become the relationships table)
As far as I understand, relationship type itself defines tables involved , so no need in storing table names.
Also, if you refactor your schema and add a common parent table for all entities that might be involved in relationship, you won't need to care about table name at all , you just store id of that new table.
Finally, relationship always has start date and may have end date, I'd suggest adding this attributes to relationships table.
As to performance, it's hard to answer without seeing how you are going to query the table. I guess in general partitioning by relationship type column will be beneficial

Generic DB Table

Is there any name for the following DB table design:
Basically we have generic columns representing key/value pair.
id | k1 | v1 | k2 | v2 | k3 | v3 | ....
1 | name | sam | last_name| smith | NULL | NULL | ...
In my application, I have many tables that have only one row and I would like to merge them into a generic table that has X number of columns with each rows representing singular table rows.
Thanks in advance.
Entity-Attribute-Value. Also called a "Name-Value Table" or an "Open Schema."
This is an SQL Antipattern. It fails many rules of relational database design, and it's incredibly hard to maintain. I recommend against it.
See more of my thoughts about EAV in my answer to the question "Product table, many kinds of product, each product has many parameters."
Bad idea. Basically you should use your relational database as a relational database.
Key/value pairs ordinarily aren't the advised storage method but at least single rows with a single key and a single value are "correct".
If you put multiple pairs in one row, it raises a number of issues:
How do you find a particular key?
Can that key be in k1, k2 or k3? Or is it always in a specific column?
How do you enforce that?
How do you make it performant?
Model your entities as entities with known attributes. That's what databases are for.

Resources