如何更好地加入我的查询

时间:2017-07-20 19:10:29

标签: sql sql-server

我的数据库中有这个结构和一些数据,结果我想要:

enter image description here

现在,我使用子查询,如下所示:

SELECT dem2.id, 
       (SELECT TOP 1 datetime 
        FROM   demand 
        WHERE  department = 'Logisitc' 
               AND action = 'Shipped' 
               AND comment = 'B' 
               AND id = dem2.id 
        ORDER  BY datetime DESC), 
       (SELECT actor 
        FROM   service_call_env 
        WHERE  id = dem2.id), 
       (SELECT TOP 1 datetime 
        FROM   demand 
        WHERE  department = 'Sale' 
               AND action = 'Email' 
               AND id = dem2.id 
        ORDER  BY datetime DESC), 
       ( Isnull((SELECT TOP 1 Isnull(Cast(demand.datetime AS VARCHAR(30)), NULL) 
         FROM 
         demand WHERE department = 'Update' AND id = dem2.id), NULL) 
         + Isnull((SELECT TOP 1 Isnull(demand.comment, NULL) FROM demand WHERE 
         department = 'Update' AND id = dem2.id), NULL) ), 
       (SELECT TOP 1 datetime 
        FROM   demand 
        WHERE  department = 'Admin' 
               AND comment IS NULL 
               AND id = dem2.id 
        ORDER  BY datetime DESC), 
       (SELECT TOP 1 dem1.datetime 
        FROM   demand 
        WHERE  department = 'Sale' 
               AND action = 'NewAddress' 
               AND id = dem2.id 
        ORDER  BY datetime DESC), 
       (SELECT TOP 1 search_name 
        FROM   demand dem1 
               INNER JOIN person 
                       ON person.person_id = dem1.USER 
        WHERE  dem1.department = 'Sale' 
               AND dem1.action = 'NewAddress' 
               AND dem1.id = dem2.id 
        ORDER  BY dem1.datetime DESC) 
FROM   demand dem1 
       INNER JOIN (SELECT id 
                   FROM   demand) AS dem2 
               ON dem1.id = dem2.id

INNER JOIN很奇怪,但我需要使用它,因为这个查询是一个更大的提取。

你能帮助我吗,因为我尝试了一些LEFT JOIN,但我的查询需要很长时间才能执行?

1 个答案:

答案 0 :(得分:1)

您可以创建一个包含所有列的临时表,并进行插入或更新以感受它们。这将使您的代码更清晰。

您需要检查表索引策略的另一点。检查表中有关在where子句上使用的列的索引,并且不要忘记在索引的include部分中包含投影列。