Mysql - 如果表中有重复项,请根据date_created列选择最旧的一个

时间:2017-12-16 14:02:54

标签: mysql

我有一张桌子,里面有讲师可用的讲座日期。结构是这样的:

+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| id           | int(11)      | NO   | PRI | NULL    | auto_increment |
| lecturer_id  | int(11)      | NO   |     | NULL    |                |
| kraj_id      | varchar(500) | YES  |     | NULL    |                |
| okres_id     | varchar(500) | YES  |     | NULL    |                |
| lecture_date | datetime     | NO   |     | NULL    |                |
| date_created | datetime     | NO   |     | NULL    |                |
+--------------+--------------+------+-----+---------+----------------+

可能存在重复lecture_date的行。 发生这种情况时,我需要根据date_created选择最早的行。尚未解决。

修改

示例数据:

+----+-------------+---------+---------------------------------------------------+---------------------+---------------------+
| id | lecturer_id | kraj_id | okres_id                                          | lecture_date        | date_created        |
+----+-------------+---------+---------------------------------------------------+---------------------+---------------------+
| 36 |          38 | 1,4,12  | 1,2,3,4,5,6,7,18,19,20,21,22,72,73,74,75,76,77,78 | 2017-12-29 00:00:00 | 2017-12-16 16:20:38 |
| 37 |          38 | 1,4,12  | 1,2,3,4,5,6,7,18,19,20,21,22,72,73,74,75,76,77,78 | 2017-12-30 00:00:00 | 2017-12-16 16:20:40 |
| 38 |          38 | 1,4,12  | 1,2,3,4,5,6,7,18,19,20,21,22,72,73,74,75,76,77,78 | 2017-12-31 00:00:00 | 2017-12-16 16:20:42 |
| 39 |          41 | 7,12    | 33,34,35,36,37,72,73,74,75,76,77,78               | 2017-12-29 00:00:00 | 2017-12-16 16:21:15 |
| 40 |          41 | 7,12    | 33,34,35,36,37,72,73,74,75,76,77,78               | 2017-12-30 00:00:00 | 2017-12-16 16:21:17 |
| 41 |          41 | 7,12    | 33,34,35,36,37,72,73,74,75,76,77,78               | 2017-12-31 00:00:00 | 2017-12-16 16:21:20 |
+----+-------------+---------+---------------------------------------------------+---------------------+---------------------+

kraj_idokres_id是讲师所涵盖的地区的ID。我按lecturer_id选择行(例如:WHERE lecturer_id IN(38,41))。如果两个或更多讲师覆盖相同的地区,lecture_date可能存在两面派。在这种情况下,我需要根据date_created选择最旧的。在上面的例子中,这将意味着选择id为36,37,38的行。

1 个答案:

答案 0 :(得分:3)

我发现了这个:

https://stackoverflow.com/a/7745679/8858190

它对我有用。我不得不对查询进行一些更改,这是最终版本:

SELECT id, lecture_date, lecturer_id, date_created 
FROM lecturer_has_dates WHERE date_created IN 
    (SELECT MIN(date_created)
    FROM lecturer_has_dates
    GROUP BY lecture_date)
AND lecture_date >= NOW() AND lecturer_id IN (38, 41)
ORDER BY lecture_date DESC

感谢你的所有建议!