简体   繁体   中英

MySQL Select first N rows from table with rows related to another one

I have a repayments table which has 16 rows for each loan that the repayments belong.

Repayments
loanid  repid  amnt
--------------------
a1      r1     1,100
a1      r2     1,100
|       |      |
a1      r16    1,105
b2      s1     2,500
b2      s2     2,500
|       |      |
b2      s16    2,510
|       |      |

Loans
loanid  othercolumns...
-----------------------
a1
b2
|
blahid
|

LoanIds are some string. RepaymentIds too

I'm looking for a query which gives me the first 15 rows from each repayments for every loan.

loanid  repid  amnt
a1      r1     1,100
a1      r2     1,100
|       |      |
a1      r15    1,105
b2      s1     2,500
b2      s2     2,500
|       |      |
b2      s15    2,510
|       |      |

Is this possible with SQL? and if so, how?

Assuming rep isn't sequential, in which case you can use WHERE rep <= 15 , then you need to introduce a row number per group. MySql does not have a built in row number function like other databases, but you can use user defined variables to achieve the same result

select *
from (
  select loan, rep, amnt, @row:=if(@prevLoan=loan, @row+1, 1) rn, @prevLoan:=loan
  from repayments
    join (select @row:=0, @prevLoan:=0) t
  order by loan, rep
  ) t
where rn <= 15

if you have some sort of ID in the other table then a simple inner join should do the trick..something like:

select t1.column1, t1.column2 
from table1 t1 
inner join table2 t2 on t1.id = t2.t1id
limit 15

hope u get it, if not post the columns and table names and i could try to give you the query you need, but this should get u started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM