这是获取所有 project_id 的结果的一种方法:
SELECT m.project_id
, COUNT(1) AS mycount
FROM ( SELECT l.project_id
, MAX(l.date) AS latest_date
FROM mytable l
WHERE l.status = 1
) m
JOIN mytable t
ON t.project_id = m.project_id
AND t.date > m.latest_date
AND t.status = 0
如果您只需要 project_id 的子集,则应将谓词添加到内联视图查询的 WHERE 子句中:
WHERE l.status = 1
AND l.project_id IN (3,5,7)
编辑
如果在最新的 status=1 行之后没有 status=0 行,则该查询不会返回一行。要返回零计数,可以使用外连接来完成。
SELECT m.project_id
, COUNT(t.status) AS mycount
FROM ( SELECT l.project_id
, MAX(l.date) AS latest_date
FROM mytable l
WHERE l.status = 1
AND l.project_id IN (3)
) m
LEFT
JOIN mytable t
ON t.project_id = m.project_id
AND t.date > m.latest_date
AND t.status = 0
为了获得最佳性能,该语句可以使用具有project_id
和date
(按该顺序)的前导列并包括该status
列的索引,例如
ON mytable (`project_id`,`date`,`status`)