Skip to content
Advertisement

SQL get records having latest association matching a specific value

Context

Using PostgreSQL, I’m storing articles and their associated events. Here is a simple structure of the 2 tables for the sake of the example:

Articles table

Events table

Problem

Here I need to be able to get all articles which have their latest events being reported.

So for example, following the data above, we must only get:

  • article 1: because it has been validated then reported
  • article 2: because it only has been reported
  • article 4: because it has been moved then reported (same as article 1)

As you can see:

  • article 3: should not be return because its latest event is validated.
  • article 5: should not be return because its latest event is moved.

I can easily find all articles having a reported event. But how to get the ones having their latest event to be reported ?

Here is what I did try to do so far without success:

We currently have:

  • 459 892 articles
  • 62 074 events

Advertisement

Answer

You could use a correlated subquery for filtering:

We could also express this with a lateral join:

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement