我需要从数据库中计算总可用数量,为此我需要与几个表进行连接。我无法粘贴整个查询,但以下是基本结构:
select sum(qty) as qty, field
from
(
(
select SUM(table1.qty) as qty , field
from
table1
left join table2 on table1.field = table2.field
left join table3 on table3.field = table2.field
where condition
group by fieldname
)
UNION ALL
(
selecy SUM(table1.qty) as qty,field
from
table1
left join table2 on table1.field = table2.field
left join table3 on table3.field = table2.field
where condition
group by fieldname
)
UNION ALL
(
select SUM(table1.qty) as qty, field
from
table1
left join table2 on table1.field = table2.field
left join table3 on table3.field = table2.field
where condition
group by fieldname
)
...
..
12 times
) as temp
LEFT JOIN another_main_table ON another_main_table.field = temp.field
我已经处理了每个表的索引,但是有一些联盟需要比预期更长的时间。此查询中使用了大约45个表,并且所有表都已完全检查。一些表有大约260万条记录。 你能告诉我如何在1/2秒内得到结果吗?截至目前,我得到了大约一分钟的结果。
答案 0 :(得分:1)
由于您给出的示例无法正确解析正确的解决方案,但是如果我粗略检查您的查询,则您使用了LEFT JOIN,因此与INNER JOIN相比,这将花费更长的时间。
因此,如果您的数据允许,请使用INNER JOIN