您的查询是正确的。您可能想看看如何在基础表中填充数据。如果您使用您建议的 SELECT 语句作为在某些 GUI 中直接编辑的表,则可能会对如何创建 2 个不同的用户行来存储数据感到困惑。
无论如何,我在 MySQL 中重建了您的示例,填充了 2 个表,如下所示:
insert into `users` (name, phone) values ('Borrower01', '123456789');
insert into `users` (name, phone) values ('Borrower02', '234567890');
insert into `users` (name, phone) values ('Borrower03', '345678901');
insert into `users` (name, phone) values ('Borrower04', '456789012');
insert into `users` (name, phone) values ('Lender03', '123456789');
insert into `users` (name, phone) values ('Lender04', '234567890');
insert into `users` (name, phone) values ('Lender01', '345678901');
insert into `users` (name, phone) values ('Lender02', '456789012');
insert into loans (amt,date,pay_period,borrower_id,lender_id)
values (100.00, '2013-04-01', '2013-04-15',1,7)
insert into loans (amt,date,pay_period,borrower_id,lender_id)
values (100.00, '2013-04-01', '2013-04-15',2,8)
insert into loans (amt,date,pay_period,borrower_id,lender_id)
values (100.00, '2013-04-01', '2013-04-15',3,5)
insert into loans (amt,date,pay_period,borrower_id,lender_id)
values (100.00, '2013-04-01', '2013-04-15',4,6)
因此,您的查询应该返回贷款 1 和 3。
Select
loans.amt,
loans.date,
loans.pay_period,
borrower.phone As borrower_phone,
borrower.name As borrower_name,
lender.phone As lender_phone,
lender.name As lender_name
From
loans Left Join
users borrower On borrower.id = loans.borrower_id Left Join
users lender On lender.id = loans.lender_id
Where
lender.phone = '123456789'
or
borrower.phone = '123456789'
这返回:
amt, date, pay_period, borrower_phone, borrower_name, lender_phone, lender_name
100, 2013-04-01, 2013-04-15, 123456789, Borrower01, 345678901, Lender01
100, 2013-04-01, 2013-04-15, 345678901, Borrower03, 123456789, Lender03
因此,您的查询格式正确。检查您的数据。