解决此 Mysql 查询的更好方法

Better approach to solving this Mysql query

我有两个 table 类似于下面的例子。我写了一个查询来组合两个 table 并得到学生的总分。总分由(caone+catwo+examscore)组成。我正在寻找在性能和语法方面是否有其他更好的方法来解决这个问题。谢谢

ca table

name  id  course  ca_cat  score
one   1    maths   1       10
one   1    maths   2       6
two   2    maths   1       9
two   2    maths   2       7     

考试table

name    id    course     score
one     1      maths       50
two     2      maths       49  

我的查询如下所示

WITH
  firstca AS (
  SELECT
    id,
    name,
    score,
    subject,
  FROM
    ca
  WHERE
    cacount =1 ),
  secondca AS (
  SELECT
    id,
    name,
    score,
    subject,
  FROM
    ca
  WHERE
    cacount=2),
  exam AS (
  SELECT
    id,
    name,
    score,
    subject,
  FROM
    exam),
  totalscore AS (
  SELECT
    fca.studentid,
    fca.name,
    fca.subject,
    fca.score AS firstcascore,
    sca.score AS secondcascore,
    ex.score AS examscore,
    (fca.score +sca.score) AS totalca,
    (fca.score+sca.score+ex.score) AS totalscores,
  FROM
    firstca AS fca
  JOIN
    secondca AS sca
  ON
    fca.studentid=sca.studentid
    AND fca.subject=sca.subject
  JOIN
    exam AS ex
  ON
    fca.studentid=ex.studentid
    AND fca.subject=ex.subject

最后的结果table可以类似这样

name    id   course caone  catwo  exam  totalscore
one      1   maths   10     6      50        66
two      2   maths    9     7      49        65    

是否有更好的方法来编写此查询,也许不使用 with 语句或使用子查询和联合?

我希望从这里的每个答案中学习。

以下适用于 BigQuery 标准 SQL

#standardSQL
SELECT name, id, course, caone, catwo, exam,
  caone + catwo + exam AS totalscore
FROM (
  SELECT name, id, course, 
    MAX(IF(ca_cat = 1, t2.score, NULL)) AS caone,
    MAX(IF(ca_cat = 2, t2.score, NULL)) AS catwo,
    ANY_VALUE(t1.score) AS exam
  FROM `project.dataset.exam` t1
  JOIN `project.dataset.ca` t2
  USING (name, id, course) 
  GROUP BY name, id, course
)  

如果应用于您问题中的示例数据 - 输出为

Row name    id  course  caone   catwo   exam    totalscore   
1   one     1   maths   10      6       50      66   
2   two     2   maths   9       7       49      65