Database Is-a relationship

孤人 提交于 2019-12-11 12:14:19

问题


My problem relates to DB schema developing and is as follows.

I am developing a purchasing module, in which I want to use for purchasing items and SERVICES. Following is my EER diagram, (note that service has very few specialized attributes – max 2)

My problem is to keep products and services in two tables or just in one table?

One table option – Reduces complexity as I will only need to specify item id which refers to item table which will have an “item_type” field to identify whether it’s a product or a service

Two table option – Will have to refer separate product or service in everywhere I want to refer to them and will have to keep “item_type” field in every table which refers to either product or service?

Currently planning to use option 1, but want to know expert opinion on this matter. Highly appreciate your time and advice. Thanks.


回答1:


I'd certainly go to the "two tables" option. You see, you have to distinguish Products and Services, so you may either use switch(item_type) { ... } in your program or entirely distinct code paths for Product and for Service. And if a need for updating the DB schema arises, switch is harder to maintain.

The second reason is NULLs. I'd advise avoid them as much as you can — they create more problems than they solve. With two tables you can declare all fields non-NULL and forget about NULL-processing. With one table option, you have to manually write code to ensure that if item_type=product, then Product-specific fields are not NULL, and Service-specific ones are, and that if item_type=service, then Service-specific fields are not NULL, and Product-specific ones are. That's not quite pleasant work, and the DBMS can't do it for you (there is no NOT NULL IF another_field = value column constraint in SQL or anything like this).

Go with two tables. It's easier to support. I once saw a DB where everything, every single piece of data went in just two tables — there were pages and pages of code to make sure that necessary fields are not NULL.




回答2:


If I were to implement I would have gone for the Two table option, It's kinda like the first rule of normalization of the schema. To remove multi-valued attributes. Using item_type is not recommended. Once you create separate tables you dont need to use the item_type you can just use the foreign key relationship.

Consider reading this article : http://en.wikipedia.org/wiki/Database_normalization

It should help.




回答3:


The problem of implementing is-a relationships in SQL tables has been explained fairly well. This problem is also sometimes called the class/subclass problem.

Here is a link to a previous answer:

Relational database design multiple user types



来源:https://stackoverflow.com/questions/13928272/database-is-a-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!