Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如果第一个查询未返回行,则条件联合执行第二个查询_Mysql_Sql_Union_Union All - Fatal编程技术网

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

我有一个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>
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。