Mysql – Database “pointers” to rows

database-designMySQLrdbms

Is there a way to have "pointers to rows" in a database?

for example I have X product rows, all these rows represent distinct products but many have the same field values except their "id" and "color_id" are different.

I thought of just duplicating the rows but this could be error prone, plus making a small change would have to be done on several rows, again buggy.


Question: Is there a way to fill some rows fully, then use a special value to "point to" certain field values?

For example:

id | field1   | field2   | field3   | color_id
-----------------------------------------------
1  | value1   | value2   | value3   | blue
2  | point[1] | point[1] | point[1] | red    (same as row 1, except id and color)
3  | point[1] | point[1] | point[1] | green  (same as row 1, except id and color)
4  | valueA   | valueB   | valueC   | orange
5  | point[4] | point[4] | point[4] | brown  (same as row 4, except id and color)
6  | valueX   | valueY   | valueZ   | pink
7  | point[6] | point[6] | point[6] | yellow (same as row 6, except id and color)

I'm using MySQL, but this is more of a general question. Also if this is goes completely against database theory, some explanation of why this is bad would be appreciated.

Best Answer

This does go against database design. Look for descriptions of normalization and relational algebra. It is bad mainly because of the comment you have made "duplicating the rows but this could be error prone, plus making a small change would have to be done on several rows, again buggy."

The idea of relational databases is to act on sets of data and find things by matching on primary and foreign keys and absolutely not to use or think of pointers at all.

If you have common data for each product, then create a product table

create table product (
  product_id int,
  field1 ...,
  field2 ...,
  field3
)
with primary key on product_id

The main table would have fields id, color_id and product_id

if product table looks like

product_id | field1   | field2   | field3  
-----------------------------------------------
1          | value1   | value2   | value3  
2          | valueA   | valueB   | valueC  
3          | valueX   | valueY   | valueZ   

The main table would look like

id | product_id | color_id
--------------------------------
1  | 1          | blue
2  | 1          | red
3  | 1          | green  
4  | 2          | orange
5  | 2          | brown
6  | 3          | pink
7  | 3          | yellow
Related Topic