D
D
Denis2021-02-07 16:28:59
SQL
Denis, 2021-02-07 16:28:59

DB query with join?

There are two
urls tables: id, name, created_at, updated_at;
and
urls_checks: id, url_id, status, created_at, updated_at;
I make a request

SELECT * FROM urls JOIN url_checks ON urls.id = url_checks.url_id

because there can be many identical url_id in url_checks I need only 1 maximum for the url_checks.updated_at field I
don't understand how to filter it? tried to add a type
HAVING/WHERE max(url_checks.updated_at)
does not work .... neither HAVING nor WHERE, tell me where to get information, if such a request is possible of course? maybe I messed up with the syntax ...
I'm trying to google, but I can't find my case.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Slava Rozhnev, 2021-02-07
@rozhnev

We use window functions:

SELECT 
  *
FROM (
  SELECT
    url_id,
    status,
    updated_at,
    ROW_NUMBER() OVER (PARTITION BY url_id ORDER BY updated_at DESC) rn
  FROM urls_checks
  ORDER BY urls_checks DESC
) checks 
JOIN urls on urls.id = checks.url_id
WHERE rn = 1;

SQL fiddle

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question