Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use OFSET and FETCH for table with JOIN

Tags:

sql

postgresql

I have a pretty simple case with two tables:

create table Table1
(
    Id int,
    Name varchar(255),
)

and

create table Table2
(
    Id int,
    Name varchar(255),
    ParentId int
)

I want to get some count of rows (for example offset 10 and fetch 5) by Table1 with joining of Table2. Between Table1 and Table2 I have a relation one-to-many.

I try to write something like that:

SELECT * 
FROM Table1 
JOIN Table2 AS t2 ON Table1.Id = t2.ParentId 
ORDER BY Table1.Id 
    OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY

As a result I get 5 rows from joined tables. But I want to get 5 rows from Table1 and then join to them Table2. Have someone any ideas how to do that?

like image 669
Alex Sofin Avatar asked Nov 22 '25 20:11

Alex Sofin


1 Answers

SELECT *
FROM (SELECT * 
      FROM Table1
      ORDER BY Id
      OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY) AS t1
JOIN Table2 AS t2 ON t1.Id = t2.ParentId

Thank you all! That was easy)

like image 156
Alex Sofin Avatar answered Nov 24 '25 10:11

Alex Sofin