MySQL视图 - 从多个表中返回NULL的计算列

问题描述 投票:0回答:1

假设我有两张桌子。表T1像:

Game Player Points Assists
 1     1     10     5
 1     2     5      10

T2喜欢:

Game Player Fouls Turnovers
1      1     5       5
1      2     10      10

我想创建一个视图,每个玩家一行和一个新的字段rating,其中rating是每个玩家的Points, Assists, Fouls,Turnovers的相等加权和。 (即评分= .25 *积分+ .25 *助攻+ .25 * Fouls + .25 *失误)

我创建了视图:

CREATE VIEW `player_view` AS (
SELECT Player,
  SUM( 
  Points *0.25 +
  Assists *0.25 +
  Fouls *0.25 +
  Turnovers *0.25) AS Rating)
FROM T1 INNER JOIN T2 ON
  T1.Player = T2.Player
AND T1.Game = T2.Game
GROUP BY Player

但不是返回一个值,我得到所有NULLRating

Player Rating
1       NULL
2       NULL

最初,我面对的是

Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'support_desk.mod_users_groups.group_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

所以我通过only_full_group_by禁用了SET sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'

所以现在,虽然视图返回结果集,但Ratings都是NULL。请协助。

mysql join group-by calculated-columns sql-view
1个回答
0
投票

似乎你错过了总和之间的操作符,例如+可能是你在关键字段中有一些隐藏的字符所以..尝试trim()

CREATE VIEW `player_view` AS 
SELECT Player,
  SUM( 
  t1.Points*0.25 + 
  t1.Assists*0.25  +
  t2.Fouls*0.25 + 
  t2.Turnovers*0.25) AS Rating
  )
FROM T1 
INNER JOIN T2 ON
  trim(T1.Player) = trim(T2.Player)
    AND trim(T1.Game) = trim(T2.Game);
GROUP BY Player

select * from player_view;
© www.soinside.com 2019 - 2024. All rights reserved.