MySQL视图-来自多个表的计算列返回NULL

时间:2019-03-26 19:36:10

标签: mysql join group-by calculated-columns sql-view

假设我有两个表。表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 *犯规+ .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

但是我没有返回值,而是为所有NULL得到了Rating

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。请协助。

1 个答案:

答案 0 :(得分: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;