简体   繁体   English

MySQL从表中选择前N行,其中行与另一行相关

[英]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. 我有一个还款表,其中每个还款所属的贷款都有16行。

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. LoanIds是一些字符串。 RepaymentIds too 也是RepaymentIds

I'm looking for a query which gives me the first 15 rows from each repayments for every loan. 我正在寻找一个查询,该查询为我提供了每笔贷款的每笔还款的前15行。

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? 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. 假设rep不是连续的,在这种情况下,您可以使用WHERE rep <= 15 ,那么您需要为每个组引入行号。 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 MySql没有像其他数据库那样具有内置的行号功能,但是您可以使用user defined variables来实现相同的结果

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: 如果您在另一个表中有某种ID,则可以使用简单的内部联接来解决问题。

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. 希望你能得到它,如果不发布列和表名,我可以尝试为你提供所需的查询,但这应该可以使你开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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