创建MySQL临时表并在PHP

时间:2015-06-07 09:41:46

标签: php mysql select temp-tables

我需要一个关于我正在编写的PHP / MySQL代码的建议。我需要做的是创建一个临时表,然后从中进行选择。问题是临时表仅在创建它的查询期间持续,因此PHP中的第二个查询为空。

以下是两个查询,我假设解决方案是将它们合并为一个单一的查询,但到目前为止我没有任何厌倦工作。

如果一个接一个地执行,下面的查询在phpMyAdmin中工作。

临时表查询:

$sql_temp_table = "CREATE TEMPORARY TABLE IF NOT EXISTS 
                   tbl_temp (id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY) AS 
                  (SELECT 
                        SUM(number_active_ads) as active_ads, 
                        MONTH(create_date) as month, 
                        YEAR(create_date) as year, 
                        dealer_id as dealer_id 
                  FROM tbl_active_ads
                  WHERE dealer_id = '".$rs->fields['id']."' 
                  GROUP BY year, month 
                  ORDER BY id)";
$rs_temp_table  =   $db -> Execute($sql_temp_table);

第二个SELECT查询:

$qry_chk_active_ads = "SELECT 
                            a.*, 
                            t.user_dealer_id, 
                            t.dealer_payment_for_month, 
                            t.dealer_payment_for_year
                       FROM tbl_temp as a
                       LEFT OUTER JOIN tbl_transaction as t
                       ON (a.dealer_id = t.user_dealer_id 
                           AND a.month = t.dealer_payment_for_month 
                           AND a.year = t.dealer_payment_for_year) 
                       ORDER BY id DESC 
                       LIMIT 3";
$rs_chk_active_ads  =   $db -> Execute($qry_chk_active_ads);

更新:当我这样做时:var_dump($rs_temp_table);我从PHP获得以下输出:

object(ADORecordSet_empty)#6(6){[" dataProvider"] => string(5)" empty" ["数据库类型"] => bool(false)[" EOF"] => bool(true)[" _numOfRows"] => int(0)[" fields"] => bool(false)[" connection"] => bool(false)}

也许这解释了为什么temp_table在PHP中似乎是空的?

1 个答案:

答案 0 :(得分:3)

为什么不简单地使用......

SELECT a.*
     , t.user_dealer_id
     , t.dealer_payment_for_month
     , t.dealer_payment_for_year
  FROM 
     ( SELECT SUM(number_active_ads) active_ads
            , DATE_FORMAT(create_date,'%Y-%m') yearmonth
            , dealer_id 
         FROM tbl_active_ads
        WHERE dealer_id = '".$rs->fields['id']."' 
        GROUP 
           BY DATE_FORMAT(create_date,'%Y-%m') 
     ) a
  LEFT 
  JOIN tbl_transaction t
    ON a.dealer_id = t.user_dealer_id 
   AND a.yearmonth = MONTH(t.dealer_payment_for_month)
   AND a.yearmonth = YEAR(t.dealer_payment_for_year) 
 ORDER 
    BY id DESC 
 LIMIT 3;