将两个查询拼接在一起的最佳方法

时间:2012-11-12 16:22:08

标签: mysql

将此查询结合在一起的最佳方法是什么:

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

1 个答案:

答案 0 :(得分: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;

由于我不知道这些表中的重复,因此group 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