优化ms sql select查询庞大的数据库

时间:2014-04-25 10:53:07

标签: sql sql-server select optimization

我的查询是

SELECT DISTINCT
    Company.Name,
    Customer.FirmID,
    Customer.ID,
    Customer.ExtendedId,
    (CustomerExtended.FirstName + ' ' + CustomerExtended.LastName) as "Customer Name"

FROM
    Company,
    Customer,
    CustomerExtended

WHERE
    (Customer.ExtendedId = 1) OR
    (CustomerExtended.FirstName = 'John' AND CustomerExtended.LastName = 'Smith')

由于数据库非常庞大,我没有设法执行此查询evan一次。我等了2个小时,但它一直在运行。有没有办法优化这个?

2 个答案:

答案 0 :(得分:4)

除非你的客户群是每一个人,否则我怀疑你的数据库实际上是非常庞大的#34;所以我认为你可能需要join你的表来获得你想要的结果

例如:

FROM
    Company 
        inner join Customer on Company.CompanyID = Customer.FirmID
    ...

有关联接的说明,请参阅http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/

答案 1 :(得分:1)

如果你需要分明你可能做错了什么。在这种情况下,您没有加入您的表(或者没有正确加入您的表,您所做的就是称为交叉连接)

SELECT 
    com.Name,
    cus.FirmID,
    cus.ID,
    cus.ExtendedId,
    cue.FirstName + ' ' + cue.LastName as [Customer Name]
FROM Company com 
JOIN Customer cus
ON com.id = cus.fk_Company
JOIN CustomerExtended cue
ON cue.fk_Customer = cus.id
WHERE
    (cus.ExtendedId = 1) OR
    (cue.FirstName = 'John' AND cue.LastName = 'Smith')

id应该是主键,fk列应该是引用主键的外键