2016-07-31 74 views
0

我有在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 

我需要存儲在bank_accounts的賬號表,並存儲在bank_customer表中的客戶號。表格bank_accounts_customers存儲客戶和他們擁有的賬戶之間的鏈接,因此多個客戶可以共享一個賬戶。數據庫中的所有表都被索引並使用外鍵來鏈接它們。

林不知如果INNER JOINJOIN會工作,以及如何做到這一點?

我附上了數據庫的圖像(這不是100%完整)。 https://s32.postimg.org/ia56fgjth/Screen_Shot_2016_07_31_at_5_51_38_pm.png

查詢,我已經試過是:

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` 
+0

如果可能的話,顯示查詢。如果您遇到任何問題,我們都會爲您提供幫助。 –

+1

因此,加入正確的聲音......你嘗試過什麼?或0努力,只是askin'? –

+0

對不起,@FirstOne我只是不確定如何在這個項目中使用它們。 –

回答

0
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 

應該得到你想要的。

+0

謝謝@Philipp,這非常棒。 –

0
select 
ba.accounts_account_number, 
bc.customers_title,bc.customers_first_name, bc.customers_middle_name, bc.customers_last_name 
from bank_accounts ba inner join bank_accounts_customers bac 
on ba.accounts_id = bac.accounts_customers_account_id 
inner join bank_customers bc 
on bac.accounts_customers_customer_id = bc.customers_id 

試試這個.. !!

+0

謝謝@Vinit Prajapati! –

0

嘗試這個

SELECT ba.accounts_account_number, bc.customers_customer_number 
FROM bank_accounts_customers bac 
INNER JOIN bank_accounts ba on bac.accounts_customers_account_id = ba.accounts_id 
INNER JOIN bank_customers bc on bac.accounts_customers_customer_id = bc.customers_id