【问题标题】:how to select multiple columns within subquery in mysql如何在mysql的子查询中选择多个列
【发布时间】:2014-06-29 20:02:19
【问题描述】:

我想定义这样的查询:

select sum(column) from table1 where id in(select column1, column2 from table2);

我该怎么做?

更新::

table1(id | base_p_id | Additional_p_id)

     1|    2    | 4

     2|    2    | 3

table2(id | desc | cost)

   2  |   -     |1200

   4  |  -      |400

现在 base_p_id & additional_p_id 是 table2 的 fk,我想取总和

喜欢

select sum(cost) from table2 where id in(select base_p_id ,additional_p_id) from table1 where id=1);

-谢谢。

【问题讨论】:

    标签: mysql


    【解决方案1】:

    你可以使用 UNION :

    SELECT
        sum(column)
    FROM
        table1
    WHERE
        id IN (SELECT col1 FROM table2 UNION SELECT col2 FROM table 2)
    

    【讨论】:

      【解决方案2】:

      您可以通过加入来做到这一点。这也将比使用带有子查询的IN 快得多:

      select sum(table1.column) 
      from table1 
      inner join table2 on table2.column1 = table1.id or table2.column2 = table1.id
      

      【讨论】:

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