简体   繁体   English

MySQL连接两个表,其中两个日期之间的日期

[英]MySQL join two tables where date between two dates

I'm having a table that contains 6 columns: id (PK, A_I), systemID (varchar(32)), total (varchar(32)), difference (varchar(16)), updated (datetime), error (int). 我有一个包含6列的表:id(PK,A_I),systemID(varchar(32)),total(varchar(32)),差异(varchar(16)),更新(datetime),错误(int )。 The table is updated every hour and right now there are over 2 million records. 该表每小时更新一次,现在有超过200万条记录。 Therefore I want to split the table up into one containing just todays values and one containing historical data. 因此,我想将表拆分为一个仅包含今天值的表和一个包含历史数据的表。 Every day at midnight data from todays table is moved to historical. 今天每天的午夜数据都会从今天的表格移至历史数据。 So far so good. 到现在为止还挺好。

Problem is that the user has the option to view the difference values in day view, week view, month view and year view. 问题在于用户可以选择在日视图,周视图,月视图和年视图中查看差异值。 I don't know how to join the today table with the historical table, so they act as one. 我不知道如何将今天的表与历史的表连接起来,所以它们充当一个表。 Presently the query for week view is: 目前,对周视图的查询是:

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

How do I join the today table with the historical table and achieve the above result? 如何将“今天”表与历史表连接起来并达到上述结果?

Try this query, 试试这个查询,

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

Also read UNION 另请阅读UNION

As mentioned above, you've done a union and your seperate queries are returning their results in their own order. 如上所述,您已经完成了并集,并且单独的查询按其自己的顺序返回了结果。 You can put the whole query into brackets, and then order the overall results: 您可以将整个查询放在方括号中,然后对整体结果进行排序:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM