在列表中放置一个返回多个列的子查询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 上的相关答案中提供了大量关于该案例的信息。