18

subquery must return only one column当我尝试运行以下查询时出现错误:

SELECT mat.mat as mat1, sum(stx.total ) as sumtotal1,
  (
    SELECT mat.mat  as mat, sum(stx.total)  as sumtotal
    FROM stx 
      LEFT JOIN mat ON stx.matid = mat.matid
      LEFT JOIN sale ON stx.saleid = sale.id
    WHERE stx.date BETWEEN '2013-05-01' AND '2013-08-31' 
      AND sale.userid LIKE 'A%'
    GROUP BY mat.mat
) AS MyField
FROM stx 
  LEFT JOIN mat ON stx.matid = mat.matid
  LEFT JOIN sale ON stx.saleid = sale.id
WHERE stx.date BETWEEN '2013-05-01' AND '2013-08-31'
  AND sale.userid LIKE 'B%'
GROUP BY mat.mat

是什么导致了这个错误?

4

2 回答 2

18

在列表中放置一个返回多个列的子查询FROM并从中进行选择。

一开始,相关的子查询将是一个坏主意。但是,您的查询甚至不相关,而是不相关(没有链接到外部查询)并且似乎返回多行。这会导致(可能非常昂贵且荒谬)交叉连接产生笛卡尔积,可能不是您的(秘密)意图。

看起来你真的想要:

SELECT m1.mat AS mat1, m1.sumtotal AS sumtotal1
      ,m2.mat AS mat2, m2.sumtotal AS sumtotal2
FROM (
   SELECT mat.mat, sum(stx.total) AS sumtotal
   FROM   stx 
   LEFT   JOIN mat ON mat.matid = stx.matid
   LEFT   JOIN sale ON stx.saleid = sale.id
   WHERE  stx.date BETWEEN '2013-05-01' AND '2013-08-31'
   AND    sale.userid LIKE 'A%'
   GROUP  BY mat.mat
   ) m1
JOIN  (
   SELECT mat.mat, sum(stx.total) AS sumtotal
   FROM   stx 
   LEFT   JOIN mat ON mat.matid = stx.matid
   LEFT   JOIN sale ON sale.id = stx.saleid
   WHERE  stx.date BETWEEN '2013-05-01' AND '2013-08-31' 
   AND    sale.userid LIKE 'b%'
   GROUP  BY mat.mat
   ) m2 USING (mat);

两者LEFT JOIN也毫无意义。一个 on被WHERE 条件sale强制为一个。INNER JOIN垫子上的那个似乎毫无意义,因为你GROUP BY mat.mat——除非你对mat IS NULL?(我对此表示怀疑。)

该案例可能可以进一步简化为:

SELECT m.mat
      ,sum(CASE WHEN s.userid LIKE 'A%' THEN x.total END) AS total_a
      ,sum(CASE WHEN s.userid LIKE 'B%' THEN x.total END) AS total_b
FROM   sale s 
JOIN   stx  x ON x.saleid = s.id
JOIN   mat  m ON m.matid = x.matid
WHERE (s.userid LIKE 'A%' OR s.userid LIKE 'B%')
AND    x.date BETWEEN '2013-05-01' AND '2013-08-31'
GROUP  BY 1;

根据WHERE您的秘密数据类型和索引,条件可能会进一步简化。在 dba.SE 上的相关答案中提供了大量关于该案例的信息。

于 2013-10-29T05:23:20.363 回答
0

而不是子查询选择语句

SELECT mat.mat  as mat, sum(stx.total)  as sumtotal

试试这个说法

SELECT sum(stx.total)  as sumtotal
于 2013-10-29T04:30:52.553 回答