Specification isn't entirely clear. But given "MY ID" value of 7, and looking for rows immediately preceding (by id
value) that have a status of 4, and we are looking to return a count of those rows, then we could do something like this:
SELECT COUNT(*) AS cnt
FROM t
WHERE t.id < 7 /* <-- MY ID -- */
AND t.id > IFNULL( ( SELECT b.id
FROM t b
WHERE NOT ( b.status <=> 4 )
AND b.id < 7 /* <-- MY ID -- */
ORDER BY b.id DESC
LIMIT 1
)
,POWER(-2,63)
)
The query is making accommodations for possibilities that id
is big integer that allows for negative values, and for NULL values of status
. The query could be simplified a bit if we had knowledge that id
is UNSIGNED, or status
is non-NULL.
The query in this answer satisfies one possible interpretation of the specification. It's also possible to modify the SELECT list to return the actual rows, rather than a COUNT(), or return the minimum id value, etc.
Note: If the status value of "4
" isn't a user-supplied value, and what we want is the value of the status
column on the immediately preceding row, we could change the query to do that.
But given the question specifies an explicit value of "4
", and there is no mention of checking the immediately preceding row to get the value of the status
column on that row, it seems a bit premature to demonstrate SQL to do something other than the specified value of "4
".