简体   繁体   English

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

[英]Combine 2 Mysql queries in to 1 (efficient way)

I have 2 tables: 我有2张桌子:

  1. The first contains data for the current day (per hour) - this table has raw data, that needs to be processed. 第一个包含当日(每小时)的数据-该表包含原始数据,需要处理。

  2. The second contains data for previous day (per day) - this table already has the values calculated for every day. 第二个包含前一天(每天)的数据-该表已经具有每天计算的值。

I want to combine this to rows in a MySQL query, so that I return the data for previous dates (per day) and for current day (again, per day). 我想将其组合到MySQL查询中的行中,以便返回以前日期(每天)和当天(再次每天)的数据。

Currently I am using 2 mysql queries: 目前,我正在使用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)";

How can I combine the 2 efficiently (speed performance is an issue)? 如何有效地将两者结合起来(速度性能是一个问题)? What would be the best way to do this? 最好的方法是什么?

Try to UNION . 尝试使用UNION Also, make sure your tables are indexed properly. 另外,请确保您的表已正确索引。 Looks like you'll want completedate and affiliateid indexed at least. 看来您至少要对completedateaffiliateid编制索引。 Not sure how much more efficient two queries is versus one union though... 虽然不确定两个查询比一个联合有多少效率...

$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`)";

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

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