Is it bad to use redundant relationships?

前端 未结 7 1094
小鲜肉
小鲜肉 2021-01-12 08:20

Suppose I have the following tables in my database:

Now all my queries depend on Company table. Is it a bad practice to give every other table a (redundant

7条回答
  •  猫巷女王i
    2021-01-12 08:51

    Is it a bad practice to give every other table a (redundant) relation to the Company table to simplify my sql queries?

    Yes, absolutely, as it would mean updating every redundant relation when you update the relations customer to company or section to company -- and if you miss any such update, you now have a database full of redundant data. It's a bad denormalization.


    If your point is to just simplify your SQL, consider using views to "bring along" parent data. Here's a view that pulls company_id into contract, by join through customer:

    create view contract_customer as
    select 
      a.*, 
      b.contract_id, b.company_id
    from 
      contract a 
      join customer b on (a.customer_id = b.customer_id);
    

    This join is simple, but why repeat it over and over? Write it once, and then use the view in other queries.

    Many (but not all) RDBMSes can even optimize out the join if you don't put any columns from customer in the select list or where clause of the query based on the view, as long as you make contract.customer_id have a foreign key referential integrity constraint on customer.customer_id. (In the absence of such a constraint, the join can't be omitted, because it would then be possible for a contract.customer_id to exist which did not exist in customer. Since you'll never want that, you'll add the foreign key constraint.)

    Using the view achieves what you want, without the time overhead of having to update the child tables, without the space overhead of making child rows wider by adding the redundant column (and this really begins to matter when you have many rows, as the wider the row, the fewer rows can fit into memory at once), and most importantly, without the possibility of inconsistent data when the parent is updated but the children are not.

提交回复
热议问题