表结构先简单说一下
table_1为父表
table_2为子表
view_1为需要进行关联的视图(数据量比较多)
最开始进行简单写一个需要达到要求的sql,要求一个月内数据取出关联视图的中对应某一个字段还要进行去重,因为在这一个月内可能存在多个同样数据并且view_1视图中也有很多重复
select
DISTINCT v.need
from
table_2 b
left join table_1 a
on b.a_id = a.id
left join view_1 v
on v.code = b.code
where
a.column1 = #{column1}
and a.column2 = #{column2}
and a.time between add_months(now(),-1)
and now();
这样写查询需要时间太长要20多秒,本来以为是因为DISTINCT函数在处理数量比较大的数据时会很慢,但是使用group by区别也并不是很大。
后来发现如果只是table_1和table_2两个表关联就很快,view_1视图只是单独查询加判断和去除就很慢将近20秒
select
v.need
from
view_1 v
where
v.code in ('code1','code2','code3','code4','code5')
group by v.need
但是只是单独查询view_1视图数据不进行in就快了很多大概五秒
于是我就有了大胆的想法,先进行view_1的视图查询再来和table_1,table_2表进行关联取数据就有了最终版本
select
DISTINCT e.need
from (
select
v.need,
v.code
from
view_1 v
where
v.column2 = #{column2}
GROUP BY v.need,v.code
) e
left JOIN table_2 b
on e.code = b.code
left JOIN table_1 a
on b.a_id = a.id
where a.column1 = #{column1}
and a.column2 = #{column2}
and a.time between add_months(now(),-1)
and now()
单是视图里查询大概五秒左右但是一起查询一秒不到,具体原因我也不太清楚,如果有同样问题的可以试一下
最后提醒一下,因为view_1是视图里面的很多东西这个查询都不需要,所以直接取出视图中相应的表进行关联就行了,不用拿整个视图来查询