我有一个包含6列的表:id(PK,A_I),systemID(varchar(32)),total(varchar(32)),difference(varchar(16)),updated(datetime),错误(int)。 该表每小时更新一次,现在有超过200万条记录。因此,我想将表拆分为仅包含今天的值和包含历史数据的表。午夜的每一天,今天表格中的数据都会移至历史数据。到目前为止一切都很好。
问题是用户可以选择查看日视图,周视图,月视图和年视图中的差异值。我不知道如何将今天的表与历史表联系起来,所以他们就像一个人一样。目前,周视图的查询是:
SELECT difference FROM productionlog
WHERE systemID = '$id'
AND DATE(updated) BETWEEN '$weekStart' AND '$weekEnd'
ORDER BY updated
如何将今天的表与历史表一起加入并获得上述结果?
答案 0 :(得分:1)
尝试此查询,
SELECT difference FROM productionlog WHERE systemID = '$id' AND DATE(updated) BETWEEN '$weekStart' AND '$weekEnd'
UNION ALL
SELECT difference FROM productionlog_today WHERE systemID = '$id' AND DATE(updated) BETWEEN '$weekStart' AND '$weekEnd' ORDER BY updated
另请阅读UNION
答案 1 :(得分:1)
如上所述,您已经完成了工会,您的单独查询会按照自己的顺序返回结果。您可以将整个查询放入括号中,然后对整体结果进行排序:
SELECT * FROM (
(SELECT difference, updated FROM productionlog WHERE systemID = '$id' AND DATE(updated) BETWEEN '$weekStart' AND '$weekEnd')
UNION ALL
(SELECT difference, updated FROM productionlog_today WHERE systemID = '$id' AND DATE(updated) BETWEEN '$weekStart' AND '$weekEnd' ORDER BY updated)
) as result
ORDER BY result.updated