There is a table called client_application with data something like this;
Id user_id name creationDate
---------------------------------------
1 5 name1 date
2 4 name2 date
3 98 name3 date
And also a table called application_status which holds the status feed of application(application_id is foreign key);
Id aplication_id status other_columns creationDate
----------------------------------------------------------------------
1 1 APPLICATION_SUMITTED data date
2 2 APPLICATION_SUMITTED data date
3 1 APPLICATION_RECEVIED data date
4 1 BANK_APPROVED data date
5 3 APPLICATION_SUMITTED data date
6 2 APPLICATION_RECEVIED data date
I want to query the application by their status. For example get the newest submitted applications? Or get the applications which the bank approved.
How can I implement such an SQL query?
I have tried thi;
SELECT *
FROM (SELECT * FROM application_status ORDER BY creationDate DESC) t1
LEFT JOIN client_application on client_application.id = t1.application_id
GROUP BY t1.application_id;
Which is fine, I can get the applications with their latest status but when I try to put a where clause in it;
SELECT *
FROM (SELECT * FROM application_status ORDER BY creationDate DESC) t1
LEFT JOIN client_application on client_application.id = t1.application_id
where t1.status = 'APPLICATION_SUBMITTED'
GROUP BY t1.application_id;
It returns all application_status has APPLICATION_SUBMITTED status column..
It returns application_id 1 item ( check the table above) but as you can see, application with the id number 1 has APPLICATION_RECEIVED status as latest status item.. So I would not expect this one in result set.
Maybe my approach is totally wrong. I’m open for any solution.
Thanks.
My advice is to improve the design of your database by creating a new table ‘Status’ for example :
You have to give the labels a logical order, and you refer to this table in your status or main table.
It will be easier to retrieve the status of an application ( where Status.Id < 3 to select all non-approved applications, or where Status.Id > 1 to select all application that are at least received ).
It is also better for maintenance purpose. This kind of logic applies in a lot of cases, and you should consider to spend a bit more time to design your data models, so you won’t spend more time resolving this kind of issue your are facing now.