2012-11-12 86 views
0

什麼是此查詢結婚在一起的最佳方式:最佳的方式共同

SELECT apvr.LIMIT, apvr.APPROVER_ID, usr.IS_ACTIVE, usr.USER_FULL_NAME   
FROM APPROVERS apvr, USER usr 
WHERE apvr.APPROVER_ID = usr.ID 

這一個:

SELECT usr.USER_FULL_NAME, COUNT(*) as numOfApprovals, MAX(APPROVAL_DATE) as lastApprovalDate  
FROM IM_APPROVAL_DETAIL appd, USER usr 
WHERE usr.ID = appd.APPROVER_ID 
GROUP By usr.USER_FULL_NAME 

+2

你必須要更具體的,可以使用聯合或連接 – jcho360

+0

是'USER'您的表中的一個?它是'MySQL'中的保留關鍵字。 – sp00m

回答

0

沒有真實的數據可能會有點辛苦,但我的建議是以下幾點:

SELECT apvr.LIMIT, apvr.APPROVER_ID, usr.IS_ACTIVE, usr.USER_FULL_NAME, count(*) as numOfApprovals, max(appd.approval_date) as lastApprovalDate 
FROM APPROVERS apvr 
JOIN USER usr ON apvr.APPROVER_ID = usr.ID 
JOIN IM_APPROVAL_DETAIL appd ON usr.ID = appd.APPROVER_ID 
GROUP By apvr.Approver_ID; 

,因爲我不知道這些表中的reoccurances的有可能BY子句一些問題與組。因此,另一種方法是使用一個子選擇:

SELECT apvr.LIMIT, apvr.APPROVER_ID, usr.IS_ACTIVE, usr.USER_FULL_NAME, appd.numOfApprovals, appd.lastApprovalDate 
FROM APPROVERS apvr 
JOIN USER usr ON apvr.APPROVER_ID = usr.ID 
JOIN IM_APPROVAL_DETAIL appd 
JOIN (
    SELECT approver_id id, count(*) numOfApprovals, max(approval_date) lastApprovalDate 
    FROM im_approval_detail 
    GROUP by id) appd 
ON appd.id = usr.ID