Managing multiple accounts and users in SQL, and assets associated with an account
I am building an application that can have multiple users from multiple accounts. For example, an account could be Company ABC. Users X, Y, and Z are members of this account. Each account should have its own separate instance so that if Company ABC creates a new DB item, it should only be visible and manageable by Company ABC. My question is this: do I have to make an explicit foreign key reference to the account in every single table in my DB? For example:
TABLE - ACCOUNTS
ACCOUNT_ID | ACCOUNT_NAME
1234 | Company ABC
TABLE - PAGES
PAGE_ID | PAGE_TITLE | ACCOUNT_ID
987 | My P开发者_Python百科age | 1234
TABLE - ASSETS
ASSET_ID | ASSET_TITLE | ACCOUNT_ID
4443 | My Asset | 1234
TABLE - GROUPS
GROUP_ID | GROUP_NAME | ACCOUNT_ID
8888 | Admins | 1234
etc?
This seems wrong to me for some reason and I feel like there is a better way that I'm not thinking of. I have nearly 75 tables that I would need to do this for. Is this right?
I have had to deal with this situation, and it is likely that you will have to include the ACCOUNT_ID column on many (though not necessarily all) your tables. An alternative is to have separate databases for each account. This can lead to maintenance problems, as you have to ensure that all changes to DDL and DML are universally applied. It also potentially leads to performance problems. Applying the column to each table does (slightly) complicate the queries joins, and views needed on the data, but joins are generally low (or no) cost in terms of performance and space. The one advantage of separate databases is that it is likely to be a more secure solution - ring-fencing each account from all others.
I suggested that not all your tables would need the account column. The need for this would depend on access paths. - For example, I have sub/super type relationships expressed in my tables. Each sub type and each super type has its own table. Access to all sub types is only through the super type, so the super type would need reference to ACCOUNTS, but the sub types would not.
EDIT: My question and the answers and comments on it, concerning this type of design question led to my above conclusion.
精彩评论