How to store data with dynamic number of attributes in a database

前端 未结 8 2331
挽巷
挽巷 2020-12-04 13:14

I have a number of different objects with a varying number of attributes. Until now I have saved the data in XML files which easily allow for an ever changing number of attr

8条回答
  •  隐瞒了意图╮
    2020-12-04 13:37

    I am assuming you do not have digital attribute soup, but that there is some order to your data.

    Otherwise, an RDBMS might not be the best fit. Something along NO SQL might work better.

    If your objects are of different types, you should generally have one table per type.

    Especially if you want to connect them using primary keys. It also helps to bring order and sanity if you have Products, Orders, Customers, etc tables, instead of just an Object and Attribute table.

    Then look at your attributes. Anything that exists more than, say for 50% of the objects in that type category, make it a column in the object's table and use null when it's not being used.

    Anything that is mandatory, should, of course, be defined as a NOT NULL column.

    The rest, you can either have one or several "extra attributes" tables for.

    You could put the attribute names into the table with the values, or normalize them out in a separate table and only use the primary key in the value table.

    You may also find that you have combinations of data. For instance, a variant of an object type always has a certain set of attributes while another variant of the same object type has another set of attributes.

    In that case, you might want to do something like:

    MainObjectTable:
      mainObjectId: PRIMARY KEY
      columns...
    MainObjectVariant1Table:
      mainObjectId: FOREIGN KEY TO MainObjectTable
      variant1Columns...
    MainObjectVariant2Table:
      mainObjectId: FOREIGN KEY TO MainObjectTable
      variant2Columns...
    

    I think the hard work, that will pay off, in the long run, is to analyze the data, find the objects and the commonly used attributes and make it into a good "object/ERD/DB" model.

提交回复
热议问题