【问题标题】:MySQL View, Union and Group ByMySQL 视图、联合和分组依据
【发布时间】:2013-03-10 10:42:30
【问题描述】:

我正在尝试编写这个 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?

【问题讨论】:

    标签: mysql sql view union


    【解决方案1】:
    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 视图中使用子查询,请将每个子查询变成一个视图,然后使用该视图而不是子查询。

    【讨论】:

    • 谢谢你!您的解释为我清除了一切,现在一切正常!
    猜你喜欢
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 1970-01-01
    • 2023-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多