2013-10-04 75 views
0

我想根據另一個表上的多個結果從一個表中返回結果。這裏的設置:具有多個結果的子選擇

Table A: "accounts" 

id | fname | other_id 

1 | test | 500 
2 | test2 | 505 
3 | test3 | 500 
4 | test4 | 540 
5 | test5 | 500 

Table B: "transactions" 

id | account_id | 

1 | 1   
2 | 4 
3 | 2 
4 | 1 
5 | 3 
6 | 2 

我試圖做到的是,返回所有的ID從交易,其中ACCOUNT_ID =表ID的WHERE other_id =一定的價值。

做手工寫出來就應該是這樣的:

因此,舉例來說,如果other_id = 500

1)得到賬戶記錄,其中other_id = 500(將多個結果,在這情況下,1,3,並從交易5)

2)得到記錄,其中ACCOUNT_ID = 1或ACCOUNT_ID = 3或ACCOUNT_ID = 5

我已經嘗試了一些不同的子查詢,但似乎無法拿出與我在找什麼。

我當然可以把它分解成使用PHP的循環,但我寧願使用單個查詢來提高效率。

+0

我認爲添加一個表與你的預期結果將比解釋它的話更容易:) –

回答

1

沒有子選擇要求,只是一個簡單的連接。

select * from accounts a, transactions t where t.account_id=a.id and other_id=500 
+0

當然......我的大腦瞬間失敗了。謝謝 :) – Jonny07

1
select t.id 
from accounts as a 
inner join transactions as t on a.id = t.account_id 
where a.other_id=500 
0

如果我理解你是對的,你想要這個。

SELECT b.id 
FROM accounts AS a 
LEFT JOIN transactions AS b ON b.account_id = a.id 
WHERE other_id = 500