mysql - 如何从以下结果中仅获取最新日期?

时间:2018-04-16 14:40:06

标签: mysql join max

我有以下表格:

    CREATE TABLE IF NOT EXISTS `interns` (
  `intern_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `f_name` varchar(20),
  `l_name` varchar(20),
  `pr_st_date` date DEFAULT NULL,
  PRIMARY KEY (`intern_id`),
  KEY `ind` (`f_name`,`l_name`)
);     

CREATE TABLE IF NOT EXISTS `interns_specialty` (
  `intern_id` smallint(10) NOT NULL,
  `specialty_id` varchar(10),
  `mentor_id` int(4) NOT NULL,
  PRIMARY KEY (`intern_id`,`specialty_id`)
);


CREATE TABLE IF NOT EXISTS `mentors` (
  `mentor_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `f_name` varchar(20) NOT NULL,
  `l_name` varchar(20) NOT NULL,
  `pr_st_date` date DEFAULT NULL,
  PRIMARY KEY (`mentor_id`)
) ;

我必须找出导师'最新的实习生日期,但我只能得到这些:

 SELECT 
mentors.l_name,
mentors.f_name,
interns.pr_st_date
FROM mentors

INNER JOIN interns_specialty
ON mentors.mentor_id = interns_specialty.mentor_id

INNER JOIN interns
ON interns_specialty.intern_id = interns.intern_id
WHERE TIMESTAMPDIFF(month, interns.pr_st_date, CURRENT_DATE)>0
;

返回重复项 - 我只需要返回日期的MAX - 导师只有1个条目(例如Bbbbbb Nick)。怎么办呢?

+---------+----------+------------+
| l_name  | f_name   | pr_st_date |
+---------+----------+------------+
| Aaaaaaa | Nick     | 2017-09-22 |
| Bbbbbb  | Nick     | 2018-01-12 |
| Bbbbbb  | Nick     | 2018-01-30 |
| Cccccc  | Nick     | 2018-02-25 |
| Ddd     | Nick     | 2018-03-16 |
| Ddd     | Nick     | 2018-01-31 |
| Xxxx    | Nick     | 2017-11-28 |
+---------+----------+------------+
7 rows in set (0.00 sec)

1 个答案:

答案 0 :(得分:1)

对于getb,只有每个mentors.l_name的最新数据,你可以使用max()和group by

  SELECT 
  mentors.l_name,
  mentors.f_name,
  max(interns.pr_st_date)
  FROM mentors

  INNER JOIN interns_specialty
  ON mentors.mentor_id = interns_specialty.mentor_id

  INNER JOIN interns
  ON interns_specialty.intern_id = interns.intern_id
  WHERE TIMESTAMPDIFF(month, interns.pr_st_date, CURRENT_DATE)>0
  group by  mentors.l_name, mentors.f_name
  ;