我有两张看起来像这样的表
用户
id
name
贷款
id
borrower_id
lender_id
amt
我需要选择所有贷款,在选择中匹配他们的名字,所以对于以下数据
用户
id, name
1, mark
2, james
贷款
id, lender_id, borrower_id, amt
1, 1, 2, 100
2, 2, 1, 150
3, NULL, 1, 500
4, NULL, 2, 300
如果贷方没有被拒绝,则为NULL。输出应该是
loan_id, lender, borrower, amt
1, mark, James, 100
2, James, mark, 100
3, --, mark, 100
4, --, mark, 100
这是我试过的
Select
loans.amt As amt,
borrower.name As borrower,
lender.name As lender,
loans.id AS loan_id
From
(users borrower Join
loans On borrower.id = loans.borrower_id) Join
users lender On lender.id = loans.lender_id
答案 0 :(得分:1)
您需要LEFT JOIN
包含只有一个表包含符合条件的行的行。
试试这个:
Select
loans.amt As amt,
borrower.name As borrower,
lender.name As lender,
loans.id AS loan_id
From
loans
LEFT JOIN users AS borrower ON loans.borrower_id = borrower.id
LEFT JOIN users AS lender ON loans.lender_id = lender.id
答案 1 :(得分:0)
在oracle中,您可以使用(+)符号而不是左连接。
例如,
选择不同 l.id为loan_id, u1.name作为贷方, u2.name作为借款人, 我是amt 来自用户u1,用户u2,贷款l 哪里 u1.id(+)= l.lender_id和 u2.id(+)= l.borrower_id