按照另一个表中列出的许多表中的公共列进行分组

时间:2014-05-20 08:05:11

标签: mysql sql database

我有一个具有以下结构的数据库。我的机构表中的每一行都有一个保存在单独表格中的每日信息。我们想要的是如何查询数据库,以便我们获得按_info表中相应天数分组的每个机构信息表的价格列总和。我的数据库是MySQL。

institutions

id | institution_name | institution_info_table_name
-----------------------------------------------------
1  | "A"              | "A_info"
-----------------------------------------------------
2  | "B"              | "B_info"

A_info

id | date       | price 
-----------------------
1  | 2013/02/12 | 12
-----------------------
2  | 2013/02/13 | 20

B_info

id | date       | price 
-----------------------
1  | 2013/02/12 | 30
-----------------------
2  | 2013/02/13 | 50

输出:

    date       | price 
    ------------------
    2013/02/12 | 42
    ------------------
    2013/02/13 | 70

编辑:

我尝试了以下查询,但它无效:

"select sum( A_info.price) ,A_info.date from A_info,B_info group by date"

2 个答案:

答案 0 :(得分:1)

这很简单,试试

select
x.date,
sum(x.price) as price
from
(
  (
    select 
    date,
    sum(price) as price
    from A_info
    group by date
  )
  union all
  (
    select
    date,
    sum(price) as price
    from B_info
    group by date
  )
)x
group by x.date

答案 1 :(得分:0)

您是否尝试过此基本查询?

select A_info.price+B_info.price from A_info, B_info where A_info.id=B_info.id and 
A_info.data=B_info.date;