dongzhabo2796 2012-10-05 07:18
浏览 101
已采纳

多个SQL表和外键

I wanted to know what is the better approach (performance wise) when working with Yii and mysql tables:

  1. 1 table with ALL the columns
  2. multiple tables (distribute the columns across them) with foreign keys relations

basically, what i'm asking is: Is there any performance degradation when a single table has many relations since Yii will fetch all the corresponding tables into the object when you do a query?

A more general question is: what is good practice and smarter approach when dealing with 1 vs multiple tables and foreign keys (again performance..)

  • 写回答

2条回答 默认 最新

  • doufenzhu7012 2012-10-05 07:22
    关注

    If performance was the only criteria in your design strategy, you would choose 1. A very bad choice, that would give you a lot of problems in a later stage of your problems.

    Databases should be designed with normalization in mind, so without any doubt, you must choose option 2!

    Update

    Example of normalized and not normalized: suppose we have a table with dvd rentals, and want to keep track of who rented the dvd:

    flat table:

    CREATE TABLE DVD (
      DvdId INT NOT NULL AUTO_INCREMENT, 
      DvdTitle varchar(64),
      Rental1 varchar(64), 
      Rental2 varchar(64), 
      Rental3 varchar(64),
      Primary Key(DvdId)
    );
    

    There is room for 3 rental entries, after that there is trouble. Beside that, when there is a extra field needed for the phone number of the customers, 3 extra fields must be made.

    First step normalization:

    CREATE TABLE DVD (
      DvdId INT NOT NULL AUTO_INCREMENT, 
      DvdTitle varchar(64),
      Primary Key(DvdId)
    );
    
    CREATE TABLE Rentals (
      RentalId INT NOT NULL AUTO_INCREMENT, 
      DvdId INT NOT NULL, 
      CustomerName varchar(64),
      RentalDate DateTime,
      Primary Key(RentalId)
    );
    

    This is better, but still not fully normalized. What if a customer rents the same dvd twice. Then there would be a double customer entry in the rentals table.

    Final:

    CREATE TABLE DVD (
      DvdId INT NOT NULL AUTO_INCREMENT, 
      DvdTitle varchar(64),
      Primary Key(DvdId)
    );
    
    CREATE TABLE Rentals (
      RentalId INT NOT NULL AUTO_INCREMENT, 
      DvdId INT NOT NULL, 
      CustomerId INT NOT NULL, 
      RentalDate DateTime,
      Primary Key(RentalId)
    );
    
    CREATE TABLE Customers (
      CustomerId INT NOT NULL AUTO_INCREMENT, 
      CustomerName varchar(64),
      Primary Key(CustomerId)
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算