I am trying to write a query for a view but I don't have a hold of it. I have two tables
user_roles
id user_id role_id
1 1 4
2 1 1
3 1 2
4 1 3
user_roles_hst
id UserRolesID RoleEnabled creator
1 1 1 1
2 1 0 1
3 1 1 1
4 2 0 1
5 2 1 1
6 3 0 1
7 4 0 1
Now i want a view with all the user roles and their latest enabled status like so
vw_user_roles
user_id role_id RoleEnabled
1 4 1
1 1 1
1 2 0
1 3 0
The user_roles_hst stores history of role status changes as they are enabled or disabled but in the vw_user_roles, i need the latest status for each or the role_id
Query:
select * from
(select x.user_id, x.UserRolesID, x.RoleEnabled from
(select h.id, u.user_id, h.UserRolesID, h.RoleEnabled from UserRoles u, UserRoles_HST h
where u.id = h.UserRolesID
group by h.id, h.UserRolesID, h.RoleEnabled, u.user_id
) x
order by x.id desc
) y
group by y.user_id, y.UserRolesID, y.RoleEnabled
I tried the above query but then i realize i can't use order by in a subquery
I need help on how to get the right query.
order byin a subquery if you also usetop 1user_roles_hststore the history without a date? Are you just assuming that the largest value ofuser_roles_hst.idmust have been added last?