您的查詢是正確的。你可能想看看你是如何填充底層表中的數據的。如果您使用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
所以,查詢是否已正確形成。檢查你的數據。
它看起來像你修剪了表格信息,所以我們不必篩選一堆額外的信息(謝謝),但是你引用了一些不在你的表格中的字段。既然你沒有收到錯誤,我猜'loan.borrower_id','loans.lender_id'和'users.id'確實存在但是沒有列出? – Windle
我已添加它們。 – Smith
我的建議是發佈每個表的一些示例數據以及查詢的所需結果。 – Taryn