简体   繁体   English

对特定 MySQL 数据库中的整个表运行查询

[英]Run query on entire table in a specific MySQL database

I have a MySQL database for storing log files.我有一个用于存储日志文件的 MySQL 数据库。

Every 30 days the system creates a new table with a name that ends with date.系统每 30 天创建一个名称以日期结尾的新表。 For example it could be log_01-11-2015 , log_01-12-2015 , etc., and store the log month-wise.例如,它可以是log_01-11-2015log_01-12-2015等,并按月存储日志。

My requirement is to search for their activity log within a date-range like starting from month January to December.我的要求是在一个日期范围内搜索他们的活动日志,比如从一月到十二月。 Writing a long SQL union query is not applicable in the web application.编写长 SQL 联合查询不适用于 Web 应用程序。 I am using php ;我正在使用php is there any way to do query within the databsse without writing a long union query by putting all the table names?有没有办法通过放置所有表名来在不编写长联合查询的情况下在数据库中进行查询? TABLE_NAME : log_01-11-2015 Table_content log_id log-date_time user_ip activity_id TABLE_NAME : log_01-11-2015 Table_content log_id log-date_time user_ip activity_id

TABLE_NAME : log_01-12-2015 Table_content log_id log-date_time user_ip activity_id And so on. TABLE_NAME : log_01-12-2015 Table_content log_id log-date_time user_ip activity_id等等。 every first of the month system creates a new table and store data month-wise每个月的第一天系统都会创建一个新表并按月存储数据

If you are using PHP, you could perhaps create your own UNION'ed query with PHP somewhat similar to this:如果您使用的是 PHP,您或许可以使用 PHP 创建您自己的 UNION 查询,有点类似于:

Test.php测试文件

<?php
$startdate = new DateTime('2015-01-01');
$enddate = new DateTime('2015-05-31');
echo getLogSQL($startdate, $enddate);

function getLogSQL($startdate, $enddate) {
    $select = 'select * from log_';
    $sql = $select . $startdate->format('Y-m');
    if ($startdate->format('Y-m') === $enddate->format('Y-m')) {
        return $sql;
    }

    while ($startdate <= $enddate) {
        $startdate = new DateTime($startdate->add(new DateInterval('P32D'))->format('Y-m-01'));
        $sql .= "\nunion all {$select}" . $startdate->format('Y-m');
        if ($startdate->format('Y-m') === $enddate->format('Y-m')) {
            return $sql;
        }
    }
}
?>

Result:结果:

$ /c/php/php.exe test.php $ /c/php/php.exe test.php

select * from log_2015-01
union all select * from log_2015-02
union all select * from log_2015-03
union all select * from log_2015-04
union all select * from log_2015-05

You can use and tweak the function to your needs with the kind of date/time format you use.您可以使用您使用的日期/时间格式类型,根据需要使用和调整该功能。

You can even add value to this function should you desire to not just get all data from the log files but also data between certain start and end dates falling within the month.如果您不仅希望从日志文件中获取所有数据,还希望获取当月内某些开始日期和结束日期之间的数据,您甚至可以为此函数添加值。

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

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