4
這裏被簡化表(sqlfiddle):各組獲取狀態由N個最後一行在MySQL
id group status
-- ------ -------
1 group1 success
2 group1 fail
3 group1 success
4 group2 success
5 group3 fail
6 group3 success
7 group3 success
8 group3 success
我需要得到有關結果由N個最後一行的失敗對每個組的信息。 這樣的(N = 3):
group has_failures
------ ------------
group1 1
group2 0
group3 0
獲得團體是很容易的:
-- Select last row from each group:
SELECT a.id, a.group, a.status
FROM log a
INNER JOIN(
select max(i.id) as max_id
from log i
group by i.group
) as b on a.id = b.max_id;
和失敗過:
-- Select fail status by last 3 rows:
select count(g.status) > 0 as has_failures
from (
SELECT a.group, a.status
FROM log a
WHERE a.group = 'group3'
ORDER BY id DESC
LIMIT 3
) as g
where g.status = 'fail';
如何應該是這兩個查詢合併,或可能更簡單的方式存在
應該不是你的'group3'行有'has_failures'等於'1'? – radoh
不,自從最後3個'group3'的條目(ids 6,7,8)都是'success' –
好的,那麼我的回答是無效的。沒有意識到你只考慮了最後3項... – radoh