MoMo
MoMo

Reputation: 422

PostgreSQL - INNER JOIN two tables with a LIMIT

I've seen this post which almost coincides with my question but my specific problem is that I need to put a limit to the third table/query, as in LIMIT 15, for example. Is there an easy way to achieve this? Thanks!

EDIT

My SQL SELECT statement would look something like this:

SELECT t2.name AS user_name, t3.name AS artist_name
FROM tbl1 t1
    INNER JOIN tbl2 t2 ON t1.t1able_id = t2.id
    INNER JOIN (SELECT * FROM tbl3 WHERE artist_id = 100 limit 15) t3
        ON t2.id = t3.artist_id
WHERE t1.kind = 'kind'

To clarify: It's just a matter of joining two tables but the second table has two states. First state as a "common user" and the next state as an "artist" (both using the same table, e.g. users).

Upvotes: 9

Views: 12200

Answers (2)

transcendx
transcendx

Reputation: 11

Few days ago I searched for such answer and Postgresql provides to do it smoothly with rank(). My goal was to get last 3 submitted annual report files before commercial firm got started its first insolvency process.

SELECT * FROM
(
    SELECT r.id, f.id AS id_file, f.file_date, min(p.process_started) AS "first_process_started",
    rank() OVER (PARTITION BY r.id ORDER BY f.file_date DESC) AS "rank"
    FROM registry r
      INNER JOIN files f ON (r.id = f.id_registry)
      INNER JOIN processes p ON (r.id = p.id_registry)
    WHERE 
      r.type = 'LIMITED_LIABILITY_COMPANY'
      AND f.file_type = 'ANNUAL_REPORT')
      AND p.process_type = ('INSOLVENCY')
    GROUP BY r.id, f.id, f.file_date
    HAVING f.file_date <= min(p.process_started)
) AS ranked_files
WHERE rank <= 3

Upvotes: 0

Pritesh Tayade
Pritesh Tayade

Reputation: 630

Try this query:

select *
from
    tableA a
        inner join
    tableB b
        on a.common = b.common
        inner join 
    (select * from tableC order by some_column limit 15) c
        on b.common = c.common

Upvotes: 5

Related Questions