好的,标题很神秘,但我不知道如何更好地进行讽刺。
我有一系列昂贵的类似SELECT SUM查询,必须按顺序执行。
示例:
SELECT SUM(t2.Field)
FROM Table1 AS t1
INNER JOIN (
SELECT Field FROM Table2
WHERE [list of where]
) AS t2 ON ti.ExtKey = t2.Key
WHERE t1.TheValue = 'Orange'
SELECT SUM(t2.Field)
FROM Table1 AS t1
INNER JOIN (
SELECT Field FROM Table2
WHERE [list of where]
) AS t2 ON ti.ExtKey = t2.Key
WHERE t1.TheValue = 'Apple'
等等。 我已经使用了嵌套的内部联接,因为经过一些测试后,它比普通的Join更快。
为Table2选择的行始终相同,或者至少对于会话而言相同。 有一种方法可以将所有查询组合在一起以加快执行速度吗?
我在考虑使用材质视图,但这会使设计和维护变得非常复杂。
答案 0 :(得分:3)
我不确定你的目标。我猜你了:
http://sqlfiddle.com/#!9/af66e/2
http://sqlfiddle.com/#!9/af66e/1
SELECT
SUM(IF(t1.TheValue = 'Orange',t2.Field,0)) as oranges,
SUM(IF(t1.TheValue = 'Apple',t2.Field,0)) as apples
FROM Table1 AS t1
INNER JOIN (
SELECT Field, `key` FROM Table2
) AS t2 ON t1.ExtKey = t2.`key`
# GROUP BY t1.extkey uncomment if you need it
如果您能提供有用的原始数据样本和预期结果。
答案 1 :(得分:0)
我想你想要一个group by
:
SELECT t1.TheValue, SUM(t2.Field)
FROM Table1 t1 INNER JOIN
(SELECT Field
FROM Table2
WHERE [list of where]
) t2
ON t1.ExtKey = t2.Key
GROUP BY t1.theValue;
请注意,您的查询没有意义,因为t2
没有名为key
的列。我认为这是对问题的疏忽。
如果要将其限制为特定值,请在WHERE
之前使用GROUP BY
子句:
WHERE t1.TheValue IN ('Apple', 'Orange', 'Pear')