【问题标题】:SQL Server index on multiple table columns多个表列上的 SQL Server 索引
【发布时间】:2018-11-05 09:09:28
【问题描述】:

我编写了一个使用两列的查询,每列都来自不同的表。如何为这些列建立索引,甚至有可能吗?

select countryName, balance
from main.country c 
join main.person p on (c.countryId = p.countryId)
where balance = (select MAX(balance) 
                 from main.person p2 
                 join main.country c2 on (c2.countryId = p2.countryId)
                 where c.countryId = c2.countryId 
                   and p.countryId = p2.countryId)
order by countryName;

【问题讨论】:

  • 您的问题似乎与stackoverflow.com/questions/8509026/… 重复。
  • 由于某种原因 sql 不允许我加入这些表 create index idx_countryperson on main.country c inner join main.person p on c.countryId=p.countryId(c.countryName, p.余额);
  • 不是 sql!该产品名为SQL Server! SQL 是许多关系数据库管理系统使用的语言。 SQL Server 仅在其中。其他包括 Oracle、MySQL、PostgreSQL、MariaDB 等等。
  • 好的,我以后就知道了

标签: sql sql-server indexing


【解决方案1】:

在 SQL Server 中,如果您想为来自不同表的列创建索引,则可以创建 Schema Bound View 并在该视图之上构建索引。

在你的情况下,创建一个模式绑定视图:

CREATE VIEW MyBoundView
WITH SCHEMABINDING  
AS  
   -- YOU QUERY 
   select countryName, balance
   from main.country c join main.person p on(c.countryId=p.countryId)
   where balance=(select MAX(balance) from main.person p2 join main.country c2 
   on(c2.countryId=p2.countryId)
   where c.countryId=c2.countryId and p.countryId=p2.countryId)
   order by countryName;  

GO  

现在您可以在此绑定视图上使用您的两列创建索引:

--Example index on the bound view.  
CREATE UNIQUE CLUSTERED INDEX IDX_V1   
   ON MyBoundView (countryName, balance);  
GO  

您可能会发现this article 很有用。

【讨论】:

    【解决方案2】:

    这是您的查询:

    select countryName, balance
    from main.country c join
         main.person p
         on c.countryId = p.countryId
    where balance = (select MAX(balance)
                     from main.person p2 join
                          main.country c2
                          on c2.countryId = p2.countryId
                     where c.countryId = c2.countryId and p.countryId = p2.countryId
                    )
    order by countryName;
    

    据我所知,您想要每个国家/地区的最高余额,以及重复项(如果有)。您可以使用以下方法获得这些:

    select top (1) with ties c.countryName, p.balance
    from main.country c join
         main.person p
         on c.countryId = p.countryId
    order by rank() over (partition by c.countryId order by p.balance desc);
    

    要按国家/地区名称排序,您需要一个子查询:

    select cp.*
    from (select top (1) with ties c.countryName, p.balance
          from main.country c join
               main.person p
               on c.countryId = p.countryId
          order by rank() over (partition by c.countryId order by p.balance desc)
         ) cp
    order by countryName;
    

    【讨论】:

    • @finsters 。 . .那里有一些一厢情愿的编程。没有论据;顺序由order by 设置。
    猜你喜欢
    • 2015-08-07
    • 1970-01-01
    • 2023-03-04
    • 2015-11-17
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 2011-10-20
    • 2017-11-19
    相关资源
    最近更新 更多