Storing “redundant” foreign keys to avoid joins

纵然是瞬间 提交于 2021-02-08 10:13:10

问题


I'm designing a database for a web application project and I came to the conclusion I may have few queries that will require a lot of joined tables to just make one check.

I'm wondering how bad is it to store the foreign key somewhere on the way to decrease number of joins required for these queries?

To give you an example of what I have at this moment: Service => Booking => Transaction => Wallet => BonusOffer

I need to check whether the service has been bought with wallet associated with a bonus. Would it be wise to store BonusOffer id as foreign key of Transaction?

You could ask why Transaction - it's because most of these queries will "go through" Transaction and Transaction will be somewhere in the middle.


回答1:


Joins are how relational DBMSs work. Learn about and use normalization.

I need to check whether the service has been bought with wallet associated with a bonus.

If this is true for every service then your database is subject to a constraint. It is that (select service from Service_has_transaction join Transaction_has_wallet) is a subset of (select service from Service_has_transaction join Transaction_has_wallet join Wallet_has_bonus).

Most SQL DBMSs don't let you express that constraint declaratively and don't know how to optimize enforcing it. However there is an SQL idiom that we can use to expresss & enforce it declaratively. (Guessing at your table definitions:) First add a bonus column to Transaction_has_wallet and a foreign key from Transaction_has_wallet (wallet, bonus) to Wallet_has_bonus. Then add wallet & bonus columns to Service_has_transaction and a foreign key from Service_has_transaction (transaction, wallet, bonus) to Transaction. This adds redundant columns but nevertheless limits the database to valid states because the foreign key constraints prevent the redundant values from being wrong. (Hopefully this is a motivatig example for learning about expressing arbitrary constraints via triggers.)



来源:https://stackoverflow.com/questions/40553231/storing-redundant-foreign-keys-to-avoid-joins

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