1

I have a master table, For e.g Fruits_Details(Master Table) which contains column name as:
f_name | f_price | location
I want to present a form to the user which consist of the above fields but also contains an additional "+" sign from which he can add new details as key, value pair.

For e.g :
fruit_color - red
fruit_season - spring
And many more details like this. I want that these two details should be stored in a different table(Child Table-I will implement foreign key concept).
But I am confused that how will design a query which will dynamically add column name and its related value in my child table.

1
  • For what it's worth, WordPress implements this key/value approach in their wp_postmeta table for assigning attributes to posts. You can look at their design for an example. It's pretty good. Commented Sep 6, 2018 at 9:56

2 Answers 2

1

The child table should have a attibute name and value there has to be nothing dynamic.

child table
-----------
fruit_id
attribute_name
attribute_value


insert into child (fruit_id, attribute_name, attribute_value)
values (1, 'color', 'red')
Sign up to request clarification or add additional context in comments.

2 Comments

But i want something like this: insert into child(fruit_id,fruit_color,fruit_location,....) values(1,'color','India'). But these column name should be dynamic, i mean if the next user wants to add fruit_season column along with its value.It should also get appended in the the child table.
Don't do it. Using dynamic structures is absolutely not recommended
0

Since the potential is endless, don't do it by columns, but by rows... You'll be able to extract the info one way, and display it another.

A table called fruits_attributes, that will contain the columns: attribute_id, f_id (foreign key), attribute_name, attribute_value

CREATE TABLE `fruits_attributes` (
  `attribure_id` int(8) unsigned NOT NULL AUTO_INCREMENT,
  `f_id` mediumint(8) unsigned NOT NULL,
  `attribure_name` varchar(50) NOT NULL,
  `attribure_value` varchar(50) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `f_id` (`offer_id`),
  KEY `attribure_name` (`attribure_name`),
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
;

Then a SELECT query should be something like

SELECT f.*, fa.* FROM
Fruits_Details f
LEFT JOIN fruits_attributes fa ON fa.id = f_id

2 Comments

But what if i want to add 3 more attributes than how will i execute it.
Anytime you add an attribute, the JOIN will add it. as long as the attribute belongs to the original master table fruit, of course

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.