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

前端 未结 8 2293
挽巷
挽巷 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:34

    If you are using a relational db, then I think you did a good job listing the options. They each have their pros and cons. YOU are in the best position to decide what works best for your circumstances.

    The serialized approach is probably the fastest (depending on your code for de-serializing), but it means that you won't be able to query the data with SQL. If you say that you don't need to query the data with SQL, then I agree with @longneck, maybe you should use a key/value style db instead of a relational db.

    EDIT - reading more of your comments, WHY are you switching to a db if speed is your main concern. What's BAD about your current XML implementation?

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题