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

我想要完成的是,从其中 account_id = 表 A 中的 id WHERE other_id = 某个值的事务中返回所有 id。

要手动写出来,它看起来像这样:

例如,如果 other_id = 500。

1) 从 other_id = 500 的帐户获取记录(将是多个结果,在本例中为 1、3 和 5)

2) 从 account_id = 1 OR account_id = 3 OR account_id = 5 的交易中获取记录

我尝试了一些不同的子选择,但似乎无法提出我正在寻找的内容。

我当然可以使用 PHP 将其分解为一个循环,但我宁愿使用单个查询来提高效率。

4

3 回答 3

1
select t.id 
from accounts as a 
inner join transactions as t on a.id = t.account_id
where a.other_id=500
于 2013-10-04T15:04:23.330 回答
1

不需要子选择,只需简单的连接。

select * from accounts a, transactions t where t.account_id=a.id and other_id=500
于 2013-10-04T15:04:36.083 回答
0

如果我理解你的话,你想要这个。

SELECT b.id
FROM accounts AS a
LEFT JOIN transactions AS b ON b.account_id = a.id
WHERE other_id = 500
于 2013-10-04T15:08:53.923 回答