优化使用别名选择子查询

时间:2017-09-05 00:06:15

标签: mysql sql

我有一个查询,从子查询中的同一个表中选择多个值

SELECT ...,
(
    SELECT IFNULL(SUM(pts), 0)
    FROM grades 
    WHERE s.id = student 
) AS spts,
(
    SELECT IFNULL(SUM(mat), 0)
    FROM grades 
    WHERE s.id = student
) AS smat,
(
    SELECT IFNULL(SUM(bio), 0)
    FROM grades 
    WHERE s.id = student
)AS sbio
FROM ...

它现在完美地工作但我认为它可以优化为一个子查询而不是3。

我尝试了什么

SELECT ...,
(
    SELECT IFNULL(SUM(pts), 0) AS spts, IFNULL(SUM(mat), 0) AS smat, IFNULL(SUM(bio), 0) AS sbio
    FROM grades
    WHERE s.id = student
)
FROM ...

但我不断收到以下错误

  

" message":SQLSTATE [21000]:基数违规:1241操作数应包含1列

预期输出

{
"spts": "89",
"smat": "44",
"sbio": "45"
}

1 个答案:

答案 0 :(得分:0)

使用left join

简化它
SELECT ...,
       COALESCE(spts, 0) as spts,
       COALESCE(smat, 0) as smat,
       COALESCE(sbio, 0) as sbio
FROM ... LEFT JOIN
     (SELECT student, SUM(pts) AS spts, SUM(mat) AS smat, SUM(bio) AS sbio
      FROM grades
      GROUP BY student
     ) g
     ON s.id = g.student;

根据FROM子句中的其他内容(以及可能的WHERE子句),这可能无法加快查询速度。