1

我有一个包含 6 列的表:id (PK, A_I), systemID (varchar(32)), total (varchar(32)), difference (varchar(16)), updated (datetime), error (int )。该表每小时更新一次,现在有超过 200 万条记录。因此,我想将表拆分为仅包含今天值的表和包含历史数据的表。今天表中的每天午夜数据都会移至历史记录。到目前为止,一切都很好。

问题是用户可以选择查看日视图、周视图、月视图和年视图中的差异值。我不知道如何将今天表和历史表连接起来,所以它们作为一个。目前周视图的查询是:

SELECT difference FROM productionlog 
WHERE systemID = '$id'
AND DATE(updated) BETWEEN '$weekStart' AND '$weekEnd'
ORDER BY updated

如何将今天表与历史表连接起来并达到上述结果?

4

2 回答 2

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

另请阅读联合

于 2013-10-01T21:47:30.260 回答
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
于 2013-10-01T22:22:02.293 回答