mysql:在一个语句中选择并求和

时间:2012-09-29 19:38:57

标签: mysql sum

我想从多个表中选择数据,我希望在一个语句中从一列中获取总和。如果我只使用sum(列)我将结果限制为一行,如果我使用group by,sum(列)似乎不起作用。或者我太傻了。

也可能有更优雅的解决方案。 (它是第6行的总和)。

SELECT 
    lb.date AS l_date, 
    gbb.id AS bid, 
    gbb.cash AS b_cash, 
    gpr.cash AS p_cash, 
    sum (gbb.cash) as t_cash,
    gbb.name
FROM 
    log_buildings lb, 
    game_building_basic gbb, 
    game_player_buildings gpb, 
    game_player_ress gpr
WHERE 
    lb.pid = :pid
    AND gpr.id = :pid
    AND gpb.pid = :pid
    AND lb.date >= gpr.date
    AND lb.bid = gbb.id
    AND gpb.buildings_id = gbb.id
    AND gpb.pid = :pid";

1 个答案:

答案 0 :(得分:0)

首先,您应该学习查询的JOIN语法:

SELECT lb.date AS l_date, gbb.id AS bid, gbb.cash AS b_cash, gpr.cash AS p_cash,
       sum (gbb.cash) as t_cash, gbb.name
FROM log_buildings lb join
     game_building_basic gbb
     on lb.bid = bgg.bid join
     game_player_buildings gpb
     on gpb.buildings_id = gbb.id join
     game_player_ress gpr
     on lb.date >= gpr.date
WHERE lb.pid = :pid AND gpr.id = :pid AND gpb.pid = :pid AND gpb.pid = :pid"

如上所述,此查询将返回所有字段的一组随机数据以及总和。您可以使用汇总来获取单独一行的总数:

SELECT lb.date AS l_date, gbb.id AS bid, gbb.cash AS b_cash, gpr.cash AS p_cash,
       sum (gbb.cash) as t_cash, gbb.name
FROM log_buildings lb join
     game_building_basic gbb
     on lb.bid = bgg.bid join
     game_player_buildings gpb
     on gpb.buildings_id = gbb.id join
     game_player_ress gpr
     on lb.date >= gpr.date
WHERE lb.pid = :pid AND gpr.id = :pid AND gpb.pid = :pid AND gpb.pid = :pid"
group by lb.date, gbb.id, gbb.cash, gpr.cash, gbb.name with rollup

但是,您希望将其作为单独的列,而不是单独的行(并且rollup会在不同的级别生成多个总和。为此,您需要一个子查询:

SELECT lb.date AS l_date, gbb.id AS bid, gbb.cash AS b_cash, gpr.cash AS p_cash,
       gbb.name,
       (select sum(gbb.cash)
        FROM log_buildings lb join
             game_building_basic gbb
             on lb.bid = bgg.bid join
             game_player_buildings gpb
             on gpb.buildings_id = gbb.id join
             game_player_ress gpr
             on lb.date >= gpr.date
        WHERE lb.pid = :pid AND gpr.id = :pid AND gpb.pid = :pid AND gpb.pid = :pid
       ) as t_cash
FROM log_buildings lb join
     game_building_basic gbb
     on lb.bid = bgg.bid join
     game_player_buildings gpb
     on gpb.buildings_id = gbb.id join
     game_player_ress gpr
     on lb.date >= gpr.date
WHERE lb.pid = :pid AND gpr.id = :pid AND gpb.pid = :pid AND gpb.pid = :pid

在几乎任何其他数据库中,您都可以使用Windows函数执行此操作:

SELECT lb.date AS l_date, gbb.id AS bid, gbb.cash AS b_cash, gpr.cash AS p_cash,
       gbb.name,sum(gbb.cash) over ()

但是MySQL不支持这种语法。