【问题标题】:Subselect with multiple results具有多个结果的子选择
【发布时间】:2013-10-04 15:01:48
【问题描述】:

我正在尝试根据另一个表的多个结果从一个表返回结果。这是设置:

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 将其分解为一个循环,但我宁愿使用单个查询来提高效率。

【问题讨论】:

  • 我认为添加一个包含预期结果的表格比用文字解释要容易:)

标签: php mysql


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:
    select t.id 
    from accounts as a 
    inner join transactions as t on a.id = t.account_id
    where a.other_id=500
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-08
        • 2011-08-25
        • 1970-01-01
        相关资源
        最近更新 更多