views:

68

answers:

2

I am setting up a MySQL database and will be querying it with PHP. Is is better to break the information up into multiple tables and do select queries on each of the tables; or is it better to put all the items in one table and do a single select query?

For example:

It will hold information on upto 7 cars; which would mean that their will be approximately 50 columns or so.

Table_design 1
----------------------
table_all
    username
    car1_make
    car1_model
    car1_year
    car1_condition
    car1_tires
    car1_color
    car2_make
    car2_model
    car2_year
    car2_condition
    car2_tires
    car2_color
----------------------

Table_design 2
----------------------
table_1
    username
    car1_make
    car1_model
    car1_year
    car1_condition
    car1_tires
    car1_color

table_2
    username
    car2_make
    car2_model
    car2_year
    car2_condition
    car2_tires
    car2_color
----------------------
+3  A: 

Three tables. This way you're not limited to the amount of information you can add to a car. And you're not limited to the number of cars a user can have access to.

If you ever need a spreadsheet of users, query the users table. If you ever need an inventory of cars, query the cars table. If you ever need to know which cars each users are associated with, query the userscars.

See Database Normalization.

  • users
    • User ID
    • User First Name
    • User Last Name
  • cars
    • Car ID
    • Car Make
    • Car Model
  • usercars
    • User ID
    • Car ID
Jonathan Sampson
I don't like the surrogate PK usage here since Make/Model information is fairly static. If you are stuck on it, I would at least UNIQUE the Make + Model (which is the true PK) to prevent more than one "car" entry of the same Make+Model from being entered. This way the table contents will actually get reused rather than duplicated. I would also add a YEAR column to the car table and include it in the make+model UK.
Kevin Peno
+1  A: 

What Jonathan said, though his table structure is many-to-many, this isn't neccesary unless multiple people might own the same car.

* users
      o User ID
      o User First Name
      o User Last Name
* cars
      o Car ID
      o User ID
      o Car Make
      o Car Model

makes more sense, and is easier to query.

MindStalker
Except that the cars table isn't truely a unique car. It's actually just storing a surrogate for the true PK of "Make and Model". So it is very likely that a single user might have multiple cars of the same make+model.
Kevin Peno