2015-09-02 163 views
0

只返回一個行我有這個疑問:加入兩個表從第二個表

SELECT t_ticket.ticketID, t_ticket.addedDate, t_ticket.question, 
t_ticket.code, t_ticket.priority, t_actionTicket.addedDateAction, t_actionTicket.title 

FROM   t_actionTicket INNER JOIN 
        t_ticket ON t_actionTicket.ticketID_FK = t_ticket.ticketID INNER JOIN 
         (SELECT  ticketID_FK, MAX(addedDateAction) AS maxDate 
          FROM   t_actionTicket AS t_actionTicket_1 
          WHERE  (t_actionTicket.userID_FK <> @userid) 
          GROUP BY ticketID_FK) AS b ON t_actionTicket.ticketID_FK = b.ticketID_FK AND t_actionTicket.addedDateAction = b.maxDate 
WHERE  (t_ticket.supporterID_FK IN 
         (SELECT  supporterID 
          FROM   t_Supporter 
          WHERE  (userID_FK = @userid))) 

我想在t_actionTicket表只返回最新紀錄爲t_ticket表中每一行t_actionTicket.userID_FK <> @用戶名。 但我有此錯誤:

The multi-part identifier "t_actionTicket.userID_FK" could not be bound.

回答

0

問題在您的查詢是

FROM   t_actionTicket AS t_actionTicket_1 
WHERE  t_actionTicket.userID_FK <> @userid -- here 

不能使用t_actionTicket別名內inner join選擇查詢。您需要使用t_actionTicket_1。這是可能只有在sub-query

嘗試做

;WITH cte 
    AS (SELECT t_ticket.ticketID, 
       t_ticket.addedDate, 
       t_ticket.question, 
       t_ticket.code, 
       t_ticket.priority, 
       t_actionTicket.addedDateAction, 
       t_actionTicket.title, 
       Row_number() 
        OVER(
        partition BY ticketID_FK 
        ORDER BY addedDateAction DESC) RN 
     FROM t_actionTicket 
       INNER JOIN t_ticket 
         ON t_actionTicket.ticketID_FK = t_ticket.ticketID 
     WHERE t_ticket.supporterID_FK IN (SELECT supporterID 
              FROM t_Supporter 
              WHERE userID_FK = @userid)) 
SELECT * 
FROM cte 
WHERE rn = 1 
0

您可以編寫使用row_number(),而不是額外的嵌套查詢這樣的邏輯:

SELECT t.ticketID, t.addedDate, t.question, t.code, t.priority, 
     ta.addedDateAction, ta.title AS Expr1 
FROM t_Ticket t INNER JOIN 
     (SELECT ta.*, 
       ROW_NUMBER() OVER (PARTITION BY ta.ticketID_FK ORDER BY ta.addedDateAction DESC) as seqnum 
     FROM t_actionTicket ta 
    ) ta 
     ON t.ticketId = ta.ticketId_FK and ta.seqnum = 1 
WHERE t.supporterID_FK IN (SELECT supporterID 
          FROM t_Supporter 
          WHERE userID_FK = @userid 
         ); 

注意,表的別名使查詢更容易編寫和閱讀。

0

嘗試此查詢

SELECT t_ticket.ticketID, t_ticket.addedDate, t_ticket.question, 
t_ticket.code, t_ticket.priority, t_actionTicket.addedDateAction, t_actionTicket.title 

FROM   t_actionTicket 
INNER JOIN t_ticket ON t_actionTicket.ticketID_FK = t_ticket.ticketID 
INNER JOIN (SELECT  ticketID_FK, MAX(addedDateAction) AS maxDate 
          FROM   t_actionTicket AS t_actionTicket_1 
          WHERE  (t_actionTicket_1.userID_FK <> @userid) 
          GROUP BY ticketID_FK) AS b ON t_actionTicket.ticketID_FK = b.ticketID_FK AND t_actionTicket.addedDateAction = b.maxDate 

WHERE  (t_ticket.supporterID_FK IN 
         (SELECT  supporterID 
          FROM   t_Supporter 
          WHERE  (userID_FK = @userid))) 
這更好的辦法
相關問題