Joining 100 tables

前端 未结 3 1976
慢半拍i
慢半拍i 2020-12-15 10:10

Assume that I have a main table which has 100 columns referencing (as foreign keys) to some 100 tables (containing primary keys).

The whole pack of information requi

3条回答
  •  太阳男子
    2020-12-15 10:52

    If your data doesn't change much, you may benefit from creating an Indexed View, which basically materializes the view.

    If the data changes often, it may not be a good option, as the server has to maintain the indexed view for each change in the underlying tables of the view.

    Here's a good blog post that describes it a bit better.

    From the blog:

    CREATE VIEW dbo.vw_SalesByProduct_Indexed
     WITH SCHEMABINDING
     AS
          SELECT 
                Product, 
                COUNT_BIG(*) AS ProductCount, 
                SUM(ISNULL(SalePrice,0)) AS TotalSales
          FROM dbo.SalesHistory
          GROUP BY Product
     GO
    

    The script below creates the index on our view:

    CREATE UNIQUE CLUSTERED INDEX idx_SalesView ON vw_SalesByProduct_Indexed(Product)
    

    To show that an index has been created on the view and that it does take up space in the database, run the following script to find out how many rows are in the clustered index and how much space the view takes up.

    EXECUTE sp_spaceused 'vw_SalesByProduct_Indexed'
    

    The SELECT statement below is the same statement as before, except this time it performs a clustered index seek, which is typically very fast.

    SELECT 
          Product, TotalSales, ProductCount 
     FROM vw_SalesByProduct_Indexed
     WHERE Product = 'Computer'
    

提交回复
热议问题