Can this MySQL db be improved or is it good as it is?

后端 未结 4 733
清酒与你
清酒与你 2020-12-21 19:22

In a classifieds website, you have several categories (cars, mc, houses etc). For every category chosen, a hidden div becomes visible and shows additional options the user m

4条回答
  •  隐瞒了意图╮
    2020-12-21 19:55

    First of all you need to create primary key for each table. Normally the best way to do this is to use sequential id field that is named either id or tablenameId. This is really important. Primary keys tied to the actual data will cause problems when the data changes.

    category (id PK, name)
    category_options (id PK, category_id FK->category.id, option_name)
    

    So that category table would have values like

    (1, car)
    (2, MC)
    

    and options would have values like

    (1, 1, year)
    (2, 1, fuel)
    (3, 2, type)
    

    Then you need a table where the values are actually stored and linked to the item. This just requires that you join all 3 category tables when you do a query for one item.

    category_values (id PK, category_options_id FK-> category_options.id, value, classified_id FK->classified.id)
    

    Classified table needs fk to poster and id field.

    classified (id PK, poster_id FK->poster.id, headline, description, hide_telephone_nr, changeable, action, price, modify_date)
    

    Poster table is quite good as it is just add id field for primary key. I just think that it is normally called users.

    By category_options_id FK-> category_options.id I mean that category_options_id should have foreign key reference to category_options.id.

    You could do even more normalizations like for classified.action and classified.changeable but it also adds complexity.

    I hope this helps.

    I must also stress that this is not the only possible solution and depending on how you actually want to use the data it might not be the best option but it works and is atleast decent :)

提交回复
热议问题