优化循环mysql结果codeigniter mysql php

时间:2016-02-03 11:45:11

标签: php mysql codeigniter

从关注表格最大值(日期)

获取结果

引导表

id   name   
75943    name1  
82501    name2 

lead_follow_up

id lead_id       msg      date       updated 
1     75943      msg1    1438930800  1438884890
2     75943      msg2    1416459600  1415901523
3     82501      msg1    1454713200  1454485087
4     82501      msg1    1439362800  1438564891

使用以下查询我得到结果

$ today_date = mktime(0,0,0,$ mon,$ day-1,$ year);

SELECT *  FROM (`lead_follow_up`) LEFT JOIN `leads` ON `leads`.`id` = `lead_follow_up`.`lead_id` WHERE `date` <=  $today_date GROUP BY `lead_follow_up`.`lead_id` ORDER BY `lead_follow_up`.`date` DESC

从上面的查询我得到数组$previou

 $previou=    Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [lead_id] => 75943
            [date] => 1438930800
            [updated_on] => 1438884890
        )

    [1] => stdClass Object
        (
            [id] => 2
            [lead_id] => 75943
            [date] => 1416459600
            [updated_on] => 1415901523
        ),
     [2] => stdClass Object
        (
            [id] => 3
            [lead_id] => 75943
            [date] => 1416459600
            [updated_on] => 1415901523
        ),....etc

);

foreach($previou as $key => $p):
    $q = "SELECT `id` FROM (`lead_follow_up`) WHERE `lead_id` = '".$p->id."' AND `date` > '".$p->date."' ORDER BY `updated_on` DESC ";
    if(!$this->db->query($q)){
        $previouData[$key] = $p;
        $pCount++;
    }
endforeach;

我真正希望看到的是像

这样的数据
id lead_id  name    msg
 1  75943 name1     msg1

在单个查询中优化此功能的任何帮助

0 个答案:

没有答案