1

我正在尝试编写此 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

我需要在这个查询中添加一个 group by,特别是在最后一个 ORDER BY Pts DESC 之前,但是添加 GROUP BY tms_id(示例),显示相同的结果。

一位朋友推荐我创建一个 VIEW,但是当我尝试显示此错误时:

#1349 - 视图的 SELECT 在 FROM 子句中包含一个子查询

而且我真的不知道什么是子查询(我搜索过但我并没有真正理解)。如何重新组织或修复此 QUERY 以使用另一个 GROUP BY?

4

1 回答 1

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 视图中使用子查询,请将每个子查询变成一个视图,然后使用该视图而不是子查询。

于 2013-03-21T03:15:11.810 回答