Mysql 如果第一个查询未返回行,则条件联合执行第二个查询
我有一个mysql查询,如下所示:Mysql 如果第一个查询未返回行,则条件联合执行第二个查询,mysql,sql,union,union-all,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
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>
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>)
现在,由于历史记录表非常庞大,而且会影响性能,所以我只想在当前日志表不返回数据的情况下执行第二个select from history。我可以以某种方式修改查询吗?尝试在第二个查询的条件下重复第一个查询,如下所示:
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>
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>)
今天的提示:切换到现代的显式连接语法!更容易编写而不出错,更容易读取和维护,并且在需要时更容易转换为外部联接。为什么不简单地执行查询1呢。如果没有结果,则执行查询2。