2013-10-04 74 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