2013-05-20 104 views
0

我必須從兩個表中選擇記錄,但在某種程度上將它們結合起來,這是我的表從同一張表中選擇兩種記錄方式?

loans 
---- 
id 
amt 
date 
pay_period 
borrower_id 
lender_id 

用戶表

users 
----- 
id 
name 
phone 

這是SQL我有

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 = '12345678' or borrower.phone = '12345678' 

預計產量爲

amt, 
date, 
pay_period, 
borrower_phone, 
borrower_name, 
lender_phone, 
lender_name, 

這個返回結果只有lender.phone =「12345678」,但如果我加入borrower.phone =「12345678」,它並不適用於這個相同的電話返回結果作爲借款人

任何意見可以理解

+0

它看起來像你修剪了表格信息,所以我們不必篩選一堆額外的信息(謝謝),但是你引用了一些不在你的表格中的字段。既然你沒有收到錯誤,我猜'loan.borrower_id','loans.lender_id'和'users.id'確實存在但是沒有列出? – Windle

+0

我已添加它們。 – Smith

+2

我的建議是發佈每個表的一些示例數據以及查詢的所需結果。 – Taryn

回答

1

您的查詢是正確的。你可能想看看你是如何填充底層表中的數據的。如果您使用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 

所以,查詢是否已正確形成。檢查你的數據。

+0

謝謝,我發現數據中有一個錯字。謝謝 – Smith

相關問題