加入2个不同列的表

时间:2013-03-13 13:02:26

标签: mysql

银行数据库架构:

account    (account_number, branch_name, balance) 
branch     (branch_name, branch_city, assets) 
customer   (customer_name customer_street, customer_city) 
loan       (loan_number, branch_name, amount) 
deposito   (customer_name, account_number) 
borrower   (customer_name, loan_number) 

我怎么知道借款人的帐号?

2 个答案:

答案 0 :(得分:5)

试试这个......(根据你的评论)

SELECT c.customer_name,
  a.account_number
FROM customer c
  INNER JOIN depositor d
    ON c.customer_name = d.customer_name
  INNER JOIN borrower b
    ON d.customer_name = b.customer_name
  INNER JOIN account a
    ON a.account_number = d.account_number

请参阅DEMO

更新:

SELECT b.customer_name,
  d.account_number
FROM borrower b
  INNER JOIN depositor d
    ON d.customer_name = b.customer_name
  INNER JOIN account a
ON a.account_number = d.account_number

请参阅DEMO

答案 1 :(得分:4)

根据您的评论,customers似乎通过accounts表格与depositor相关联。如果是这样,那么你可以使用:

select c.customer_name,
  a.account_number,
  a.balance
from customer c
inner join depositor d
  on c.customer_name = d.customer_name
inner join account a
  on d.account_number = a.account_number

请参阅SQL Fiddle with Demo

如果您想知道借款人的帐号,那么您将在borrower表中添加一个JOIN:

select c.customer_name,
  a.account_number,
  a.balance
from customer c
inner join depositor d
  on c.customer_name = d.customer_name
inner join account a
  on d.account_number = a.account_number
inner join borrower b
  on c.customer_name = b.customer_name

您的数据库设计似乎有一些问题。根据您当前的结构,如果您想了解borrowers,则必须加入depositor以获取帐号或loan表以将贷款与帐户相关联

如果您加入loan表,则查询将为:

select b.customer_name,
  a.account_number
from borrowers b
inner join loan l
  on b.loan_number = l.loan_number
inner join account a
  on l.branch_number = a.branch_number

但问题是loan表只能在account加入branch_number,此分支号码将与多个帐户相关联。您应该有一个列,用于标识每个borrower的{​​{1}},因为缺少此列,您目前无法找到每个借款人的帐号。