在单个sql查询中一起使用JOIN和group

时间:2012-12-07 11:50:31

标签: mysql select join group-by

我无法一起使用JOINS和group-by: 我搜索了这个......但我找不到解决方案..问题如下:

我有两个表,第一个是main_table,其中包含字段eidnamestatus

第二个表是对字段fideidlast_dateremarksnext_date

的跟进

第二个表用于存储客户端的后续详细信息(存储在main_table中的客户端详细信息),我希望获得具有所选日期周期(from_date到to_date)的每个客户端的最后一个后续记录,并按降序排序next_date。

我使用了以下查询但没有工作

SELECT * 
FROM main_table as MT 
JOIN followups as MF on MT.eid=MF.eid 
WHERE MT.status='open' AND MF.NDate<='2012-12-07' 
GROUP BY MF.eid 
ORDER BY MF.next_date DESC

提前感谢......伙计们

3 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情:

select m.eid,
  m.name,
  m.status,
  f1.last_date,
  f1.remarks,
  f1.next_date
from maintable m
left join
(
  select max(last_date) maxLast, eid
  from followups
  where last_date between from_date and to_date
  group by eid
) f
  on m.eid = f.eid
left join followups f1
  on f.maxLast = f1.last_date
  and f.eid = f1.eid
where m.status='open'
  and f1.next_date<='2012-12-07'
order by f1.next_date desc

答案 1 :(得分:1)

试试这个:

SELECT * FROM main_table AS MT 
LEFT JOIN (SELECT * FROM (SELECT * FROM followups WHERE NDate<='2012-12-07' ORDER BY next_date DESC) AS A GROUP BY eid) AS MF ON MT.eid=MF.eid 
WHERE MT.status='open';

答案 2 :(得分:1)

试试这个

SELECT * FROM main_table AS MT 
LEFT JOIN (SELECT * FROM (SELECT * FROM followups ORDER BY next_date DESC) AS A GROUP BY eid) AS MF ON MT.eid=MF.eid 
WHERE MT.status='open' 
AND MF.NDate<='2012-12-07';