This does not solve my problem
SQL Join to the latest record
I want to join tables in such a way that it fetches only the latest record from one of the tables using MySQL and also count the read_reciept columns with specific value
The following are my datas.
Table_One:
ID | Name |
---|---|
1 | John |
2 | Tom |
3 | Anna |
Table_two:
ID | Visit ID | Date | read_reciept |
---|---|---|---|
1 | 2513 | 5/5/2001 | 1 |
1 | 84654 | 10/5/2012 | 1 |
1 | 454 | 4/20/2018 | 1 |
2 | 754 | 4/5/1999 | 0 |
2 | 654 | 8/8/2010 | 1 |
2 | 624 | 4/9/1982 | 1 |
3 | 7546 | 7/3/1997 | 0 |
3 | 246574 | 6/4/2015 | 1 |
3 | 15487 | 3/4/2017 | 1 |
Results needed after Join:
ID | Name | Visit ID | Date | read_reciept |
---|---|---|---|---|
1 | John | 454 | 4/20/2018 | 3 |
2 | Tom | 654 | 8/8/2010 | 2 |
3 | Anna | 246574 | 6/4/2015 | 2 |
3
Answers
Use sub-query with
row_number
to get only the last row from thattable_two
.Here
row_number
will number row with the sameID
based on order bydate
column.Later during join we take only rows with the value being produced equal 1, which means in this case – oldest.
Assuming you’re up to an 8.0 release, you have two options:
If you’re on an older release, well condolences first of all. 5.7 and older don’t even really qualify as a modern database, and hasn’t for a long time. But this is still possible.
If you are using an old version of mysql then try this :
Steps to do it :
First we need to get the latest date :
Then we get the related
Visit_ID
and sum(read_reciept):And Finally we join our data using
INNER JOIN
to get the expected resultDemo here