今天业务需求中需要用到UNION,SQL如下:
select p.id as id, p.`column` as `column`, p.`value` as `value`, p.history_begin_time as history_begin_time, p.history_end_time as history_end_time
from cmdbcoresvrdb.p_fixednetworkelement p
WHERE p.id = 0x11E8A2BD695CD4C692DB286ED288C859 and p.history_begin_time >= 1564649660400 and p.history_end_time <= 1564649840600
UNION
select p.id as id, p.`column` as `column`, p.`value` as `value`, p.history_begin_time as history_begin_time, p.history_end_time as history_end_time
from cmdbcoresvrdb.p_fixednetworkelement p
WHERE p.id = 0x11E8A2BD695CD4C692DB286ED288C859 and p.history_begin_time < 1564649660400
ORDER BY history_begin_time DESC LIMIT 1
运行之后发现UNION执行不正常,只有后边select的结果
后来在UNION后边加上了小括号,问题解决
select p.id as id, p.`column` as `column`, p.`value` as `value`, p.history_begin_time as history_begin_time, p.history_end_time as history_end_time
from cmdbcoresvrdb.p_fixednetworkelement p
WHERE p.id = 0x11E8A2BD695CD4C692DB286ED288C859 and p.history_begin_time >= 1564649660400 and p.history_end_time <= 1564649840600
UNION
(select p.id as id, p.`column` as `column`, p.`value` as `value`, p.history_begin_time as history_begin_time, p.history_end_time as history_end_time
from cmdbcoresvrdb.p_fixednetworkelement p
WHERE p.id = 0x11E8A2BD695CD4C692DB286ED288C859 and p.history_begin_time < 1564649660400
ORDER BY history_begin_time DESC LIMIT 1)