1

我想从多个表中选择数据,并且我想从一个语句中的一列中获取总和。如果我只使用 sum (column),我会将结果限制为一行,如果我使用 group by,sum (column) 似乎不起作用。或者我只是太愚蠢了。

也可能有一个更优雅的解决方案。(它在第 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";
4

1 回答 1

1

首先,您应该学习查询的 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 不支持这种语法。

于 2012-09-29T21:02:32.490 回答