mysql将3个查询合并为3个类别的SUM

时间:2013-12-29 08:42:13

标签: php mysql sum multiple-tables

我有3个查询,我想将其合并为一个以便于访问

$query = "SELECT r.member_id, m.name, m.class, m.classid, m.level,m.guild_title, SUM(achie_points) total_pvp\n"
. "FROM roster_addons_achievements_achievements as r\n"
. "LEFT JOIN roster_addons_achievements_achie AS c \n"
. "ON r.achie_id = c.achie_id\n"
. "LEFT JOIN roster_members AS m\n"
. "ON r.member_id = m.member_id\n"
. "WHERE c.c_id = 95 OR c.p_id = 95\n"
. "GROUP BY r.member_id,m.name\n"
. "ORDER BY r.member_id ASC";

给我c_id 95和p_id 95的SUM(achie_points)

$query2 = "SELECT r.member_id, SUM(achie_points) total_arena\n"
. "FROM roster_addons_achievements_achievements as r\n"
. "LEFT JOIN roster_addons_achievements_achie AS c \n"
. "ON r.achie_id = c.achie_id\n"
. "LEFT JOIN roster_members AS m\n"
. "ON r.member_id = m.member_id\n"
. "WHERE c.c_id = 165\n"
. "GROUP BY r.member_id,m.name\n"
. "ORDER BY r.member_id ASC";

给我c_id 165的SUM(achie_points)

$query3 = "SELECT r.member_id, SUM(achie_points) total_rbg\n"
. "FROM roster_addons_achievements_achievements as r\n"
. "LEFT JOIN roster_addons_achievements_achie AS c \n"
. "ON r.achie_id = c.achie_id\n"
. "LEFT JOIN roster_members AS m\n"
. "ON r.member_id = m.member_id\n"
. "WHERE c.c_id = 15092\n"
. "GROUP BY r.member_id,m.name\n"
. "ORDER BY r.member_id ASC";

给我c_id 15092的SUM(achie_points)

我结合3的问题是c_id 95,165和15092的SUM(achie_points) 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

$query = "SELECT r.member_id, m.name, m.class, m.classid, m.level,m.guild_title,
                 SUM(IF(c.c_id = 95 OR c.p_id = 95, achie_points, 0)) total_pvp,
                 SUM(IF(c.c_id = 165, achie_points, 0)) total_arena,
                 SUM(IF(c.c_id = 15092, achie_points, 0)) total_rbg
          FROM roster_addons_achievements_achievements as r
          LEFT JOIN roster_addons_achievements_achie AS c 
          ON r.achie_id = c.achie_id
          LEFT JOIN roster_members AS m
          ON r.member_id = m.member_id
          WHERE c.c_id IN (95, 165, 15092) OR c.p_id = 95
          GROUP BY r.member_id,m.name
          ORDER BY r.member_id ASC";

答案 1 :(得分:0)

您也可以通过union运算符组合它们,但是3个查询必须具有相同的输出格式。