PostgreSQL - INNER JOIN两个带LIMIT的表

时间:2013-06-03 08:41:58

标签: sql ruby-on-rails postgresql

我看过this帖子几乎与我的问题一致,但我的具体问题是我需要对第三个表/查询设置限制,例如LIMIT 15。有没有一种简单的方法来实现这一目标?谢谢!

修改

我的SQL SELECT语句看起来像这样:

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'

澄清:这只是加入两个表的问题,但第二个表有两个状态。第一个状态为“普通用户”,下一个状态为“艺术家”(均使用相同的表格,例如users)。

2 个答案:

答案 0 :(得分:3)

尝试此查询:

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

答案 1 :(得分:0)

几天前,我搜索了这样的答案,而Postgresql提供了使用 rank()使其顺利完成的功能。 我的目标是在商业公司开始其第一个破产程序之前,获取最后3份提交的年度报告文件。

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