gpt4 book ai didi

MySQL View 、联合和分组依据

转载 作者:行者123 更新时间:2023-11-29 06:50:46 25 4
gpt4 key购买 nike

我正在尝试编写此 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(示例),显示相同的结果。

一个 friend 推荐我创建一个VIEW,但是当我尝试显示这个错误时:

#1349 - View's SELECT contains a subquery in the FROM clause

而且我也不是很清楚什么是子查询(我搜索了一下也不是很懂)。我如何重新组织或修复此 QUERY 以使用另一个 GROUP BY?

最佳答案

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 View 中使用子查询,请将每个子查询放入一个 View ,然后使用该 View 而不是子查询。

关于MySQL View 、联合和分组依据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15538773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com