与mysql联合的麻烦

时间:2012-06-14 10:49:46

标签: mysql union

我遇到了一些问题(包括技术问题和概念问题),优化了一些非常慢的查询。

这是我原来的疑问:

select Con_Progr,
    Pre_Progr
from contribuente,
    preavviso_ru,
    comune,
    via
where [lots of where clauses]
    and ((Via_Progr = Con_Via_Sec) or (Via_Progr = Con_Via_Res and (Con_Via_Sec is null or Con_Via_Sec = '0')))
order by Con_Cognome,
    Con_Nome asc;

此查询大约需要38秒执行,这是一个非常慢的时间。我稍微操纵了它并设法加速到大约0.1秒,现在查询看起来像这样:

(select Con_Progr,
    Pre_Progr
from preavviso_ru
    join contribuente
        on Pre_Contribuente = Con_Progr
    join via
        on Via_Progr = Con_Via_Sec
    join comune
        on Via_Comune = Com_CC
where [lots of where clauses]
order by Con_Cognome,
    Con_Nome asc
)
union
(
select Con_Progr,
    Pre_Progr
from preavviso_ru
    join contribuente
        on Pre_Contribuente = Con_Progr
    join via
        on Via_Progr = Con_Via_Res
    join comune
        on Via_Comune = Com_CC
where [lots of where clauses]
    and (Con_Via_Sec is null or Con_Via_Sec = '0')
order by Con_Cognome,
    Con_Nome asc
)

正如您所看到的,我在原始查询中拆分了where子句,该子句在两个不同的子查询中使用了OR运算符,然后合并它们。这解决了速度问题。结果虽然不完美,因为我失去了订单。我尝试在子查询中选择列,然后对该结果执行排序,如下所示:

select Con_Progr,
        Pre_Progr
from (
    [FIRST SUBQUERY]
) as T1 union (
    [SECOND SUBQUERY]
) as T2
order by Con_Cognome,
        Con_Nome asc

但是我在“union”附近收到语法错误。有什么建议吗?

这是技术问题。现在对于概念,我认为这两个子查询非常相似(它们只有join子句和where子句不同),有没有办法以更优雅的方式重新排列第二个查询(快速查询)?

1 个答案:

答案 0 :(得分:0)

我解决了技术问题,我错了括号:

select Con_Progr,
    Pre_Progr
from (
    [FIRST SUBQUERY]
union
    [SECOND SUBQUERY]
) as T
order by Con_Cognome,
    Con_Nome asc

现在它几乎完美地工作(订购中仍然存在一些差异,但这不是问题。

关于查询的效率,我发现问题是两个不同列上的OR条件,因为MySQL 4.0(我用于向后兼容性问题)只允许表的一个索引。但是,为什么它至少不使用其中一个索引。我会再测试一下......

相关问题