在php中使用sql的复杂查询

时间:2015-07-14 07:28:49

标签: php mysql sql

我有一个问题,

我需要创建一个复杂的选择查询,我不能这样做:

所以我有多个数据库调用cluster1,cluster2,cluster3,...,cluster10,

每个群集都有一个表格游戏。我需要在过去7天内获取所有集群的一些行。 我试过这样:

foreach ($aDataBases as $database) {
   $sFlashParties = sprintf('
       SELECT left(depart, 10) as date, count(*) as nb 
       FROM `%s` 
       WHERE duree>0 and depart 
       BETWEEN current_date()-7 AND current_date() 
       GROUP BY date', $sFlashTableName);
   $r_count = Mysqli::query($sFlashParties, $database);
   $a_row = $r_count->fetch_array(MYSQLI_ASSOC);
   error_log(print_r($a_row,true), 3, "/tmp/error.log");
}

结果必须是:

Day       Nb_total
你能帮帮我吗? Thx提前

2 个答案:

答案 0 :(得分:1)

给定与具有多个数据库的主机的单个连接,构建并执行如下所示的查询字符串。

请注意使用反引号运算符来指示database.table位置。

编辑:您只是从每个查询中获取第一个结果,通过这样做来解决:

<?php

$databases = array("cluster1","cluster2","cluster3","cluster10");

foreach ($databases as $db) {
    $sFlashtableName = '`' . $db . '`.`games`';
    print sprintf('SELECT left(depart, 10) as date, count(*) as nb 
       FROM %s 
       WHERE duree>0 and depart 
       BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE() 
       GROUP BY date', $sFlashtableName) . PHP_EOL;

    // execute the query in this loop and store the results in an array
    // parse the array later and aggregate your results
    // $totals[] = queryresult;

    $r_count = Mysqli::query($sFlashParties, $database);

    while($a_row = $r_count->fetch_array(MYSQLI_ASSOC);){
        $rows[] = $row; // this will add every result line from all databases into one single array
        $rows[$$db][] = $row; // not tested!, but this should give you something like similar to this $rows[cluster2] = array($a_row['date'],$a_row['nb']);
    }
}

/*
SELECT left(depart, 10) as date, count(*) as nb
       FROM `cluster1`.`games`
       WHERE duree>0 and depart
       BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()
       GROUP BY date
SELECT left(depart, 10) as date, count(*) as nb
       FROM `cluster2`.`games`
       WHERE duree>0 and depart
       BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()
       GROUP BY date
SELECT left(depart, 10) as date, count(*) as nb
       FROM `cluster3`.`games`
       WHERE duree>0 and depart
       BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()
       GROUP BY date
SELECT left(depart, 10) as date, count(*) as nb
       FROM `cluster10`.`games`
       WHERE duree>0 and depart
       BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()
       GROUP BY date
*/

您可以选择接下来的结果。

答案 1 :(得分:0)

使用DATE_SUB()计算“一周前”的日期

从这里参考

https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-sub