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”,它不会返回与借用者相同的电话的结果

任何建议将被认真考虑

4

1 回答 1

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

因此,您的查询格式正确。检查您的数据。

于 2013-05-20T19:22:01.717 回答