I have user_status table it consist of different users and their status( A,B,C,D) now my requirement is status A should get compare with all other status(B,C,D) and get only record of status A value if status A updated time is greater then all other status but status A is processed before (B,C,D) so updated time is less compare to other status then in this scenario don't get any record
id user_id status updated
1 1 C 2023-12-28 23:32:06
2 1 B 2023-12-28 23:34:06
3 1 A 2023-12-28 23:36:06
4 2 B 2023-12-27 23:12:02
5 2 D 2023-12-27 23:15:08
6 2 A 2023-12-27 23:18:06
7 2 C 2023-12-27 23:22:06
Expected output : id=3 For user-1 record should get=> for this user recent status is A and B,C,D processed before A so priority is given to Status A
For user-2 no record should get because status A must processed last however it got already processed and hence last status for this user is C
Mysql query :
SELECT t1.*
FROM table t1
INNER JOIN table t2 on t2.status=t1.status where t1.status='A' and t1.updated > t2.updated
Based on my reading of your question, it seems that for each
user_idvalue you want to compare theupdatedvalue for the row withstatus= 'A' with theupdatedvalue for the rows withstatus<>Aand select theArow if itsupdatedvalue is greater than theupdatedvalue for the other rows. If so, then the following should work.Schema (MySQL v5.7)
Query #1
View on DB Fiddle
Note
The join condition
... AND u.status = 'A' ...is not really necessary since given thatu.updated > sq.max_updated, then thestatuscolumn value must be 'A'. So we really only need:But if we changed the condition
u.updated > sq.max_updatedtou.updated >= sq.max_updated, then we would have to add the additional testu.status = 'A'because there will always be at least one non-'A' row for whichu.updated >= sq.max_updated.Further Explantion
Consider the following subquery (you can refer to the db fiddle, which I have updated to show what the subquery yields):
This creates one row for each unique
user_idwith two columns, theuser_idandmax_updated, which is the greatest value of theupdatedcolumn for thatuser_idconsidering only rows whoseuser_statusis not 'A':Then for a given
user_idif there is a correspondinguser_statusrow withstatus= 'A' that has anupdatedcolumn greater than this subquery'smax_updatedvalue, then we then wish to select that row. We can determine such rows by joining theuser_statustable with the above subquery using the appropriate join conditions. Note that this is not a self join, which is when you join a table with itself. In this case we are joining theuser_statustable with a subquery that is based on theuser_statustable but which is not theuser_statustable itself.