Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set up Table to store variable number of fields per record?

How should I set up my database / table, if I do not know the number of fields I would populate per record?

For example, if I have a web form that allows a user to enter all the cars he owns, and I don't want to limit him to a certain number, how would I store this in the database end?

The above problem extends to similar situations such as storing a user's order (variable number of items per order) etc.

like image 464
xbonez Avatar asked Oct 29 '11 18:10

xbonez


People also ask

How many fields is too many in a table?

More information. In Access, you can define up to 255 fields in a table. If you create 255 fields and then delete 10, Access does not release the fields from the internal column count.

What is a set of fields and records?

Collection of fields is called records. In a database, a record is a group of fields within a table that are relevant to a specific entity. Records are composed of fields, each of which contains one item of information. A set of records constitutes a file.

How many fields should a database table have?

There is no constraint on number of fields in database theory. A table can be limited to a primary key (even if this primary key is made of 2 fields), meaning that Apocalisp's answer is not very clear. At the opposit, a table can be made out of thousends of fields, as long as normal form rules are respected.


2 Answers

In Relational Database Management Systems (RDBMS) instead you create child records in a dependent table that relate child entities (cars) with parent entities (users). There is a concept known as database normalization, and the objective is that each table contains data for a single type of entity.

So you have a user table with the user information:

user_id | user_name | email             | ...
  1234  | User1     | [email protected] | ...
  2356  | User2     | [email protected] | ...

Then another table for storing the information of each car of a user:

user_car_id | user_id | car_label | make      | model | ...
          1 |   1234  | MyCar     | Ford      | 2011  | ...
          2 |   2356  | A Car     | Chevrolet | 2010  | ...
          3 |   1234  | MyOtherCar| BMW       | 2000  | ...

So instead of storing the info of the cars in the user table, you have a table for storing car (user_car) information related to each user by way of the user_id column. This is an example of a one-to-many relationship, in which one user can have many related cars.

like image 96
Xint0 Avatar answered Oct 31 '22 05:10

Xint0


this is an entire topic: database normalization.

the short answer is you make more than one table.

in your example you would have person table, a car table, and a third that linked person to the car

like image 38
Randy Avatar answered Oct 31 '22 06:10

Randy