MySQL加入和子查询

时间:2012-01-16 16:16:31

标签: mysql

我目前有以下表格:

Case_Workflows

case_id (PK)  |  work_id (PK)  |    date
     1        |     1          |  2011-12-12
     1        |     4          |  2011-12-13
     2        |     6          |  2011-12-18

工作流

  work_id (PK)  |  status_id
     1          |     1
     2          |     1
     3          |     1
     4          |     2
     5          |     2
     6          |     3

以下状态

  status_id (PK)  |   title
     1            |     abc
     2            |     def
     3            |     ghi

我试图做的是抽取具有特定状态(例如'abc')的案例总数。问题在于,每个案例都可以有多个工作流程,我只想要每个案例中最新的一个。

最终结果应为:

状态:abc - 数量:2

这是我到目前为止所做的:

SELECT COUNT(cases.case_id) as countNum  
FROM $this->_caseTable  
JOIN case_workflows 
  ON cases.case_id = cases_workflows.case_id  
JOIN workflows 
  ON cases_workflows.workflow_id = workflows.workflow_id  
JOIN statuses 
  ON workflow.status_id = statuses.status_id
WHERE cases.date > '2011-12-12'
AND cases.date <= '2011-12-18' 

我不确定的是如何首先为每个案例选择最新的work_id,然后抓取其status_id以将其与WHERE子句匹配,例如WHERE statuses.title = 'abc'

2 个答案:

答案 0 :(得分:2)

SELECT COUNT(*) as countNum  
FROM $this->_caseTable  
JOIN workflows 
  ON workflows.workflow_id =  
     ( SELECT workflow_id 
       FROM cases_workflows AS mcwf
       WHERE mcwf.case_id = cases.case_id
       ORDER BY date DESC 
       LIMIT 1
     )
JOIN statuses 
  ON workflow.status_id = statuses.status_id
WHERE cases.date > '2011-12-12'
  AND cases.date <= '2011-12-18'
  AND statuses.title = 'abc'

答案 1 :(得分:1)

根据我的理解,您需要将statuses.title添加到SELECT子句中,然后添加GROUP BY子句:

SELECT statuses.title, COUNT(cases.case_id) as countNum  
FROM $this->_caseTable  
JOIN (SELECT case_id, work_id, max(date) 
      FROM case_workflows 
      GROUP BY work_id 
      WHERE case_id = cases.case_id) cw 
  ON cases.case_id = cw.case_id  
JOIN workflows 
  ON cw.workflow_id = workflows.workflow_id  
JOIN statuses 
  ON workflow.status_id = statuses.status_id
GROUP BY statuses.title
WHERE cases.date > '2011-12-12'
AND cases.date <= '2011-12-18'