簡體   English   中英

MySQL從表中選擇前N行,其中行與另一行相關

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

我有一個還款表,其中每個還款所屬的貸款都有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是一些字符串。 也是RepaymentIds

我正在尋找一個查詢,該查詢為我提供了每筆貸款的每筆還款的前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
|       |      |

SQL可能嗎? 如果是這樣,怎么辦?

假設rep不是連續的,在這種情況下,您可以使用WHERE rep <= 15 ,那么您需要為每個組引入行號。 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

如果您在另一個表中有某種ID,則可以使用簡單的內部聯接來解決問題。

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

希望你能得到它,如果不發布列和表名,我可以嘗試為你提供所需的查詢,但這應該可以使你開始。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM