In Mysql I have the following table - property_alert_status
having columns :
id (primary), propertyId, status, updatedAt
All record - select * from property_alert_status
id | propertyId | status | updatedAt |
---|---|---|---|
1 | 1 | ALERT | 1658304031 |
2 | 2 | OK | 1658300273 |
3 | 3 | ALERT | 1658312336 |
4 | 3 | ALERT | 1658313979 |
5 | 3 | OK | 1658312336 |
6 | 2 | OK | 1658312336 |
From the above table, I want to fetch the most recent record for the property based on status. If Status is 'ALERT' then most recent 'ALERT' record otherwise Most recent 'OK' record.
Ex - For propertyId '3' there are three records but most recent alert status is of id 4 so the output for the above propertyId 3 should be:
id | propertyId | status | updatedAt |
---|---|---|---|
4 | 3 | ALERT | 1658313979 |
Expected Output should be:
id | propertyId | status | updatedAt |
---|---|---|---|
1 | 1 | ALERT | 1658304031 |
4 | 3 | ALERT | 1658313979 |
6 | 2 | OK | 1658312336 |
I have made one query but the output is not as expected:
Select mainStatus.* from (
SELECT *
FROM property_alert_status
ORDER BY
(CASE
WHEN status = "ALERT" THEN 0
ELSE 1
END) ASC, updatedAt DESC
) mainStatus group by propertyId;
Innerquery is giving the right result but when selecting only a single record by grouping propertyId, giving the wrong result.
Inner query giving result:
id | propertyId | status | updatedAt |
---|---|---|---|
4 | 3 | ALERT | 1658313979 |
3 | 3 | ALERT | 1658312336 |
1 | 1 | ALERT | 1658304031 |
5 | 3 | OK | 1658312336 |
6 | 2 | OK | 1658312336 |
2 | 2 | OK | 1658300273 |
The final query gives result:
id | propertyId | status | updatedAt |
---|---|---|---|
1 | 1 | ALERT | 1658304031 |
2 | 2 | OK | 1658300273 |
3 | 3 | ALERT | 1658312236 |
Note: Using Mysql v5.6.50.