两个不同表的分组行的总和

时间:2014-05-15 16:37:50

标签: php mysql

我以某种方式坚持一项非常简单的任务......

我有两张桌子:

TABLE A:
name  time
name1 100
name2  50
name1 200
name3 100
name2  50

TABLE B:
name time
name3 100
name1  50
name3 200
name2 100
name1  50

我想拥有的是前两个名字总数最多的名单!

像这样的东西(但是这不是工作)

SELECT  a.name 
        , SUM(a.time) as time1
        , (SELECT SUM(time) FROM table2 b WHERE b.name = a.name GROUP BY a.name) as time2
        , time1 + time2 as total
FROM table1 a
GROUP BY a.name
ORDER BY total DESC
LIMIT 2

提前致谢!

2 个答案:

答案 0 :(得分:1)

我会选择以下内容:

SELECT
  name,
  SUM(time) AS total_time
  FROM (
    SELECT name, time FROM table_a
    UNION ALL
    SELECT name, time FROM table_b
  ) AS u
  GROUP BY name
  ORDER BY total_time DESC
  LIMIT 2
;

这里有working sqlfiddle个数据。

答案 1 :(得分:0)

试试这个...

SELECT name, SUM( timeA + timeB ) AS total
FROM (
    SELECT name, time as timeA, 0 as timeB
    FROM a
    UNION ALL
    SELECT name, 0 as timeA, time as timeB
    FROM b
) AS times
GROUP BY name
ORDER BY total DESC