2014-04-11 4 views
1

내가다음 절차를 어떻게 향상시킬 수 있습니까?

SELECT t1.accountid, t1.accountbalance 
FROM transactionstable t1 
WHERE transactiondate = (SELECT MAX(transactiondate) 
      FROM transactionstable 
      WHERE accountid = t1.accountid); 

이 거기에 다음 쿼리에게 절을 가진 사용 예를 들어 선택한 두 번째를 대체 할 수있는 방법을 가지고, 나는 그것을 빨리해야하기 때문에 수행하는 방법 (계정 아이디는 외래 키) 및 transactiondate는있다 그것에 색인.

감사합니다.

답변

3

당신은 transactiondate ,accountid에 복합 인덱스가 도움이 될 것 대신에 또한 하위 쿼리

SELECT t1.accountid, 
t1.accountbalance  
FROM transactionstable t1 
JOIN (SELECT accountid ,MAX(transactiondate) transactiondate 
      FROM transactionstable 
      GROUP BY accountid) t 
USING (transactiondate ,accountid) 

accountid 그룹 당 날짜의 최대 값과 자기 JOIN을 사용할 수 있습니다

create index my_idx on my_table(transactiondate ,accountid); 
+0

나는 다음과 같은 오류가 : \ n 'having clause'에서 'transactiondate'알 수없는 열 \ ni 테이블에서 열 이름을 복사했습니다. + t1.transactiondate를 시도했지만 동일한 오류가 나타납니다. –

+0

@ user3518239 내 업데이트보기 당신이 내 대답의 이전 버전을 사용 대답 (대답) –

+0

(transactiondate, accountid)가 고유하지 않기 때문에 나는 여전히 당신의 도움이 필요합니다, 그래서 나는 다른 질문에 게시 : [여기에 질문입니다] (http://stackoverflow.com/questions/23105757/how-to-correct-this-query-in-mysql-that-giving-me-the-first-transaction-when-im) –

관련 문제