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