如果第一个不返回行,则条件联合执行第二个查询

时间:2017-03-08 07:31:10

标签: mysql sql union union-all

我有一个mysql查询如下:

select m.field1, l.field2... l.fieldn
from mytable m, logtable l
where <some conditions to join m and l>

union

select m.field1, h.field2... h.fieldn
from mytable m, loghistorytable h
where <some conditions to join m and h>

现在由于历史表非常庞大并且达到了性能,我只想在当前日志表没有返回数据的情况下执行历史记录中的第二个选择。我能以某种方式修改查询吗?

1 个答案:

答案 0 :(得分:0)

尝试在第二个查询的条件下重复第一个查询,如下所示:

select m.field1, l.field2... l.fieldn
from mytable m, logtable l
where <some conditions to join m and l>

union

select m.field1, h.field2... h.fieldn
from mytable m, loghistorytable h
where <some conditions to join m and h>
and not exists (select m.field1, l.field2... l.fieldn
                from mytable m, logtable l
                where <some conditions to join m and l>)