doulangdang9986 2016-07-31 16:53
浏览 40
已采纳

根据关系表值从另一个表中选择

I have three tables in MySQL:

1) bank_accounts

- accounts_id (PRIMARY)
- accounts_account_number (UNIQUE)

2) bank_accounts_customers

- accounts_customers_id (PRIMARY)
- accounts_customers_account_id (INDEX)
- accounts_customers_customer_id (INDEX)

3) bank_customers

- customers_id (PRIMARY)
- customers_customer_number (UNIQUE)
- customers_title
- customers_first_name
- customers_middle_name
- customers_last_name

I need to get the Account Number stored in the bank_accounts table and the Customer Number stored in the bank_customer table. The table bank_accounts_customers stores a link between the customers and the accounts that they have so multiple customers can share one account. All tables in the database are indexed and using Foreign Keys to link them.

Im unsure if INNER JOIN or JOIN would work and how to do this?

I have attached an image of the database (that is not 100% complete). https://s32.postimg.org/ia56fgjth/Screen_Shot_2016_07_31_at_5_51_38_pm.png

The query that I have tried is:

SELECT `bank_accounts`.`accounts_account_number`, `bank_customers`.`customers_customer_number`
FROM `bank_accounts`, `bank_customers`
INNER JOIN `bank_accounts_customers`
ON bank_accounts_customers`.`accounts_customers_account_id` = `bank_accounts`.`accounts_id`
  • 写回答

3条回答 默认 最新

  • dsf6565 2016-07-31 17:00
    关注
    SELECT ba.accounts_account_number, bc.customers_customer_number 
    FROM bank_accounts AS ba
    
    INNER JOIN bank_accounts_customers AS bac
     ON bac.accounts_customers_account_id = ba.accounts_id
    
    INNER JOIN bank_customers AS bc
     ON bc.customers_id = bac.accounts_customers_customer_id 
    

    Should get what you want.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line