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 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题