我正在尝试编写此SQL查询:
Select t1.tms_id, t1.tms_name, t1.Pts from (
SELECT t.tms_id, t.tms_name, SUM(s.lsc_1stscore) as Pts FROM tb_team as t,tb_league as l, tb_game as g, tb_score as s
WHERE (t.tms_id = l.lgs_1stplace) AND (l.fk_lsc_id = s.lsc_id) AND (t.fk_gms_id = g.gms_id) AND (g.gms_id = 1)
GROUP BY t.tms_name
) t1
union
Select t2.tms_id, t2.tms_name, t2.Pts from (
SELECT t.tms_id, t.tms_name, SUM(s.lsc_2ndscore) as Pts FROM tb_team as t,tb_league as l, tb_game as g, tb_score as s
WHERE (t.tms_id = l.lgs_2ndplace) AND (l.fk_lsc_id = s.lsc_id) AND (t.fk_gms_id = g.gms_id) AND (g.gms_id = 1)
GROUP BY t.tms_name
) t2
union
Select t3.tms_id, t3.tms_name, t3.Pts from (
SELECT t.tms_id, t.tms_name, SUM(s.lsc_3rdscore) as Pts FROM tb_team as t,tb_league as l, tb_game as g, tb_score as s
WHERE (t.tms_id = l.lgs_3rdplace) AND (l.fk_lsc_id = s.lsc_id) AND (t.fk_gms_id = g.gms_id) AND (g.gms_id = 1)
GROUP BY t.tms_name
) t3
union
Select t4.tms_id, t4.tms_name, t4.Pts from (
SELECT t.tms_id, t.tms_name, SUM(s.lsc_4thscore) as Pts FROM tb_team as t,tb_league as l, tb_game as g, tb_score as s
WHERE (t.tms_id = l.lgs_4thplace) AND (l.fk_lsc_id = s.lsc_id) AND (t.fk_gms_id = g.gms_id) AND (g.gms_id = 1)
GROUP BY t.tms_name
) t4
ORDER BY Pts DESC
我需要在此查询中添加一个组,特别是在最后一个ORDER BY Pts DESC之前,但添加GROUP BY tms_id(示例),显示相同的结果。
朋友建议我创建一个VIEW,但是当我尝试向我显示此错误时:
#1349 - View的SELECT包含FROM子句中的子查询
而且我真的不知道什么是子查询(我搜索过,而且我并不理解)。如何重新组织或修复此QUERY以使用另一个GROUP BY?
答案 0 :(得分:2)
Extract.
Select t1.tms_id, t1.tms_name, t1.Pts from (
SELECT t.tms_id, t.tms_name, SUM(s.lsc_1stscore) as Pts FROM tb_team as t,tb_league as l, tb_game as g, tb_score as s
WHERE (t.tms_id = l.lgs_1stplace) AND (l.fk_lsc_id = s.lsc_id) AND (t.fk_gms_id = g.gms_id) AND (g.gms_id = 1)
GROUP BY t.tms_name
) t1
以下是上面sql语句中的子查询。
SELECT t.tms_id, t.tms_name, SUM(s.lsc_1stscore) as Pts FROM tb_team as t,tb_league as l, tb_game as g, tb_score as s
WHERE (t.tms_id = l.lgs_1stplace) AND (l.fk_lsc_id = s.lsc_id) AND (t.fk_gms_id = g.gms_id) AND (g.gms_id = 1)
GROUP BY t.tms_name
要在mysql视图中使用子查询,请将每个子查询放入视图中,然后使用该视图而不是子查询。