将2个Mysql查询合并为1(高效方式)

时间:2011-12-23 03:18:12

标签: php mysql left-join multiple-tables

我有两张桌子:

  1. 第一个包含当天(每小时)的数据 - 此表包含需要处理的原始数据。

  2. 第二个包含前一天(每天)的数据 - 此表已包含每天计算的值。

  3. 我想将它与MySQL查询中的行组合在一起,以便我返回之前日期(每天)和当天(再次,每天)的数据。

    目前我正在使用2个mysql查询:

    //table 1, data for current day
                        $qry1="
                select DATE_FORMAT(completedate,'%Y-%m-%d') as date, SUM(IF(complete = 1,affpayout,0)) as pay, COUNT(*) as leads
                from leads
                where affiliateid={$_SESSION["id"]}  AND completedate>'$date' 
                GROUP BY DATE_FORMAT(completedate,'%Y-%m-%d')";
    //table 2, data for previous days, already processsed, we just need to select it
                $qry2="
                select DATE(date) as date, affrevenue as pay, totalleads as leads
                from leadsdays
                GROUP BY DATE(date)";
    

    如何有效地结合2(速度性能是一个问题)?最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

尝试UNION。此外,请确保您的表已正确索引。看起来您至少需要completedateaffiliateid索引。不确定两个查询与一个联盟相比效率更高......

$qry = "(select 
    DATE_FORMAT(completedate,'%Y-%m-%d') as `date`, 
    SUM(IF(complete = 1,affpayout,0)) as pay, 
    COUNT(*) as leads
    from leads
    where affiliateid={$_SESSION["id"]}  AND completedate>'$date' 
    GROUP BY DATE_FORMAT(completedate,'%Y-%m-%d')) 
    UNION 
    (select 
    DATE(`date`) as `date`, 
    affrevenue as pay, 
    totalleads as leads
    from leadsdays
    GROUP BY DATE(`date`)) 
    ORDER BY DATE(`date`)";