9

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).

Yashu Mittal
  • 1,478
  • 3
  • 14
  • 32
MoMo
  • 422
  • 3
  • 5
  • 14

2 Answers2

5

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
Pritesh Tayade
  • 630
  • 4
  • 11
  • 2
    When using `limit` you should also apply an `order by` otherwise the result is "random" –  Jun 03 '13 at 08:47
  • You can use MAX or MIN too to limit for a specific table. – Kees Sonnema Jun 03 '13 at 08:54
  • I'm sorry, I just realized it's not using three tables but two. I have edited my question to be more specific. – MoMo Jun 03 '13 at 09:05
  • 1
    @KeesSonnema As per my understanding aggregate functions like `MAX() MIN()` will return only 1 row , it is not a alternate for `limit`.. as `limit` restricts the `resultset` to specified number. – Pritesh Tayade Jun 03 '13 at 12:23
0

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