S
S
Sergey Nitka2014-01-13 15:48:41
MySQL
Sergey Nitka, 2014-01-13 15:48:41

Is it good to duplicate FOREIGN KEY, ENUM values ​​to other tables?

For example:
There is a table of orders
id | order_name | type order | client_id
1 | test_name | default | 1
2 | test_name | default | 2
3 | test_name | default | 3
4 | test_name | default | 4
There is a second table with
id | order_id | offer_name
1 | 1 | test_offer_name
2 | 1 | test_offer_name
3 | 2 | test_offer_name
4 | 3 | test_offer_name
Let's say we need to find out from which client the offer number {check_offer_id} was received
(For clarity, let's assume that the result of the selection can be placed in a variable)

var order_id = SELECT order_id FROM offers WHERE id = {check_offer_id};
SELECT client_id FROM orders WHERE id = {order_id};
SELECT * FROM users WHERE id = {client_id};

We are smart people and will not make three requests to the database. Indexes are worth - do LEFT JOIN
SELECT `u`.* FROM offers as `of` 
LEFT JOIN orders as `or` ON (`of`.order_id = `or`.id)
LEFT JOIN users as `u` ON(`or`.client_id = `u`.id)

We will get all the information about the client in one request!
Now what is the crux of the matter. Is it good/bad to place it in a table with client_id and type clauses, thereby duplicating the keys so as not to make unnecessary queries to the
id | order_id | offer_name | client_id | type
1 | 1 | test_offer_name | 1 | default
2 | 1 | test_offer_name | 1 | default
3 | 2 | test_offer_name | 2 | default
4 | 3 | test_offer_name | 3 | default
This is an abstract example. There are a lot of such tables in the project, operations are performed very often, and in order to get some data from the table by key, you need to do 3-5 joins.
(For example, imagine that the users table has the city_id field, and the city table has the admin_area_id field, and the country table has the country_id field in the table with regions. And imagine what query you need to do to get the country ID in order to collect statistics in general in a separate table by country .

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nazar Mokrinsky, 2014-01-13
@Rumzik

In the general case, such duplication is called denormalization, and in the case when the normalized "beautiful" version does not cope with the load, it is necessary to use a structure that is not so beautiful, but more efficient for a particular task.
There is nothing wrong with JOIN, but if this is a bottleneck for you, then yes, such a change takes place.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question