如何优化此SQL查询?

时间:2010-01-26 16:37:10

标签: sql sql-server aggregate

我有3张桌子:

  • CRSTasks(ID,parentID)
  • CRSTaskReceivers(ID,tskID,receiverID)
  • UserNames(id,name)

... CRSTasks和CRSTaskReceivers之间的关系一对多 UserNames和CRSTaskReceivers之间的一对一

tasks   
ID   parent  
1     null    
10     1      
50     1

taskReceivers  
id      taskID    receiverID  
1        1          4(john)  
1        10         2(mike)  
1        50         3(brand)  

我需要这样的结果:

taskid    Receivers
------------------- 
1           jone,mike,brand   

仅限于父母的任务,这将会使接收者感到意外

2 个答案:

答案 0 :(得分:2)

SQL Server 2005 +:


SELECT t.id AS taskid,
       STUFF((SELECT ','+ x.name
                FROM (SELECT COALESCE(pu.[ArabicName], aut.Name) AS name
                        FROM CRSTaskReceivers tr 
                        JOIN AD_USER_TBL aut ON aut.id = tr.receiverid
                   LEFT JOIN PORTAL_USERS pu ON pu.id = aut.id
                       WHERE tr.crstaskid = t.id
                         AND tr.receivertype = 1
                      UNION
                      SELECT agt.name
                        FROM CRSTaskReceiver tr
                        JOIN AD_GROUP_TBL sgt ON agt.id = tr.receiverid
                       WHERE tr.receivertype = 3
                         AND tr.crstaskid = t.id) x
         FOR XML PATH('')), 1, 1, '')
  FROM CRSTasks t

不需要这个功能。

答案 1 :(得分:1)

除了奇数字符串连接之外,确实看起来所有可以在一个查询而不是四个查询中完成。在连接中有多个标准是完全没问题的。一些事情:

FROM   CRSTaskReceiver
   INNER JOIN CRSTask
        ON  CRSTaskReceiver.CRSTaskID = CRSTask.ID
   INNER JOIN CRS_BuiltinGroup
        ON  CRSTaskReceiver.ReceiverID = CRS_BuiltinGroup.ID AND CRSTaskReceiver.ReceiverType = 4
WHERE  CRSTask.ParentTask = @TaskID

此功能的以下部分似乎绝对没有。这意味着什么?

DECLARE @tmpLength INT
SET @tmpLength = 0
SET @tmpLength = LEN(@tmp)
IF @tmpLength > 0
BEGIN
    SET @tmp = SUBSTRING(@tmp, 0, @tmpLength)
END 
相关问题