+--------------+-----------------+-----------+---------------------+
| hierarchy_id | title | parent_of | created_date |
+--------------+-----------------+-----------+---------------------+
| 1 | Muscat | 0 | 2014-01-01 00:00:00 |
| 2 | Bahrain | 1 | 2014-01-01 00:00:00 |
| 3 | Kuwait | 2 | 2014-01-01 00:00:00 |
| 4 | Jordan | 2 | 2014-01-25 00:00:00 |
+--------------+-----------------+-----------+---------------------+
hierarchy_id 3 和 4 具有相同的“parent_of”2。 我只想从中选择一个具有最大日期的。
我的预期结果是:
+--------------+-----------------+-----------+---------------------+
| hierarchy_id | title | parent_of | created_date |
+--------------+-----------------+-----------+---------------------+
| 1 | Muscat | 0 | 2014-01-01 00:00:00 |
| 2 | Bahrain | 1 | 2014-01-01 00:00:00 |
| 4 | Jordan | 2 | 2014-01-25 00:00:00 |
+--------------+-----------------+-----------+---------------------+
最佳答案
您可以选择 max of created_date,然后按 parent_of 分组。查询将如下所示
SELECT max(hierarchy_id) as hierarchy_id,title,parent_of,max(created_date) as created_date
FROM tableName
GROUP BY parent_of
关于MySQL:按最大日期分组和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26958169/