Vishwanth Iron Heart
Vishwanth Iron Heart

Reputation: 734

how do i create a sql which takes the last inserted record of each unique record?

I have a table (inspect) which gets filled every time an inspector visits the station.

When an admin tries to view the inspect table, i would want to display all the records which satisfy these conditions:

  1. Each record must hold unique station name

  2. Displayed record must be the last updated record for that particular station

As of now, the sql I've used is

$sql = "select `StationID`,`DOI`,`due`,`StationName` from inspect group by `StationID`";

This displays perfectly, except it shows the first record of each unique station.

E.g. if the table has

StationID StationName      DOI         due
924         RMC      17-Mar-2014
924         RMC      20-Mar-2016    
926         IMD      23-Jan-2018                
926         IMD      18-Jan-2018                
926         IMD      18-Jan-2018                
926         IMD      18-Jan-2018     19-Jan-2019    

my sql must display

924 RMC 20-Mar-2016
926 IMD 18-Jan-2018 19-Jan-2019

Upvotes: 0

Views: 73

Answers (2)

Ben Thurley
Ben Thurley

Reputation: 7161

There are some big if's to this answer since the question really needs clarifying. However, it is possible if we make the following assumptions.

  • StationName is what you want to group by
  • StationID is a unique incrementing ID (the primary key)

The following query would work.

select a.StationID, a.DOI, a.due, a.StationName from inspect a
where a.StationID = (
  select max(b.StationID) from inspect b  
  where b.StationName = a.StationName
)
group by a.StationName;

As evidenced in this fiddle

Back to those assumptions... I think to achieve what you want, you must have a primary key. So if StationID isn't the primary key then you need to add one and use that column instead.

Edit
The question has now changed because as I suspected it had mistakes. You can group on StationID or StationName and get the same result so that bit doesn't matter. But I don't think you can get the results you want with that table structure.

First you need a way to get the "last updated record". You currently don't have a column that tells you this. The DOI column apparently gives you a clue but it is not unique and you have three rows there with the same date. The due column can't be relied upon because it is mostly null.

Second, once you have that column you have no way of using it to select only that record within the group by. You can only do this with a primary key. It's not a good table design if you don't have a means to refer to one row. It completely rules out any type of join.

Upvotes: 1

kjdion84
kjdion84

Reputation: 10054

$sql = "select * 
        from `inspect` 
        group by `StationID` 
        order by str_to_date(`DOI`, '%d-%b-%Y') desc";

You need to convert the DOI column to an actual date so that it can be ordered by the engine appropriately.

Upvotes: 0

Related Questions