2016-02-01 86 views
0

獲得從如下表最大的結果(日期)Mysql的加入獲得最大的日期相關的表項

導致表

id name 
1 name1 
2 name2 
3 name3 

遵循

id lead_id msg  date 
1  1  msg1 20-01-2015 
2  1  msg2 22-01-2015 
3  1  msg3 24-01-2015 
4  2  msg22 21-01-2015 
5  3  msg31 22-01-2015 
6  3  msg32 24-01-2015 

什麼我真的很期待看到數據如

lead_id name msg  date 
    1  name1 msg3 24-01-2015 
    2  name2 msg22 21-01-2015 
    3  name3 msg32 24-01-2015 

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

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

目前即時通訊做加盟兩種表的表和使用的foreach發現最大日

foreach($resultarray as $p){ 
SELECT `id` FROM (`follow`) WHERE `lead_id` = ".$p->id." AND `date` > ".$p->date." ORDER BY `updated_on` DESC" 
} 

任何幫助在單個查詢優化該

回答

0

給這個一展身手:

SELECT 
    lead_id, 
    NAME, 
    msg, 
    a.date 
FROM lead 
    JOIN (
     SELECT 
      lead_id, 
      max(date) AS date 
     FROM follow 
     GROUP BY lead_id 
    ) a 
    ON lead.id = a.lead_id 
    JOIN (
     SELECT 
      lead_id, 
      date, 
      msg 
     FROM follow 
    ) b 
    ON lead.id = b.lead_id 
    AND a.date = b.date 
0

可以使用LEFT JOIN查找follows中的所有行,其中不存在具有相同lead_id的較新行。之後,您可以像往常一樣加入leads以獲得結果;

SELECT l.id lead_id, l.name, f.msg, f.date 
FROM follow f 
LEFT JOIN follow f_newer 
    ON f.date < f_newer.date AND f.lead_id = f_newer.lead_id 
JOIN leads l 
    ON f.lead_id = l.id 
WHERE f_newer.lead_id IS NULL 

A simple SQLfiddle to test with

您也可以通過查找每個lead_id的最大日期並使用它查找正確行的子查詢來執行此操作;

SELECT l.id lead_id, l.name, f.msg, f.date 
FROM follow f 
JOIN leads l 
    ON f.lead_id = l.id 
WHERE (lead_id, date) IN (SELECT lead_id, MAX(date) FROM follow GROUP BY lead_id) 

Another SQLfiddle

相關問題