多次联合查询同一张表

时间:2021-05-27 10:41:06

标签: sql tsql

Select c.id
from Customer c
     inner join Orders o on (o.cid=c.id)
     where c.companyid=?
union 
     Select c.id
     Customer c
     inner join RecentOrder ro on (ro.cid=c.cid)
     where c.companyid=?

如何提高查询的性能?我的客户表有一个“companyid”的 50k 数据,因此订单和RecentOrder 表也有大量数据。如何提高查询性能?

3 个答案:

答案 0 :(得分:0)

我建议使用 or

select c.id 
from Customer c 
where exists (select 1
              from Order o
              where o.cid = c.id
             ) or
      exists (select 1
              from RecentOrder o
              where o.cid = c.id and c.companyid = ?
             );

对于子查询,您需要在 Orders(cid)RecentOrders(cid) 上建立索引。

答案 1 :(得分:0)

如果您确定这些查询将返回相同的记录,我的建议是使用 union all。由于您有更多的记录,它会提高性能。 Union all 的性能受到了影响,因为它正在选择参与者中的独特记录。

您的查询有语法错误,我已在此答案中更正。如果你想过滤union的记录,在union all查询中获取记录后去派生表。

      Select 
        c.id
      from Customer c
       inner join Order o 
            on o.cid=c.id
       where c.companyid=''

       union  all

       Select 
        c.id
      from Customer c
        inner join RecentOrder ro 
          on ro.cid=c.cid
         where c.companyid=''

答案 2 :(得分:0)

[Customer]表添加非聚集索引,将通过查找和减少字段查找来改进。但是,它无法避免对[Order][RecentOrder] 进行扫描。如果您已经设置了这些表之间的关系,则 sql 优化器可能会正常工作。

    CREATE NONCLUSTERED INDEX [IX_Companyid_Customerid] ON [dbo].[Customer]
    (
        [companyid] ASC
    )
    INCLUDE ([id])
    GO

它是 mssql 的示例代码。