Mysql join获取与日期相关的最大日期表条目

时间:2016-02-01 04:57:24

标签: 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"
}

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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