选择具有最新时间戳的行

时间:2017-04-25 13:01:24

标签: mysql sorting

实际上我的数据库包含两个主要的城市表和城市。天气,我想选择最新的气象表条目。

看起来大概是这样的:

plz     cities_plz description name         modified
9020      9020     looks great Klagenfurt   24.04.2017
9020      9020     rain        Klagenfurt   25.04.2017
9020      9020     rain        Klagenfurt   10.04.2017
9100      9100     sunny       Villach      25.04.2017

所以现在,我只想获得最新的条目。我已经用这个命令尝试了它:

select   * 
from     weather, cities 
WHERE    weather.cities_plz = cities.plz 
ORDER BY modfified DESC;

问题是,这个cmd并没有放弃这些dublicates ...... 有任何想法吗?会很感激的!

5 个答案:

答案 0 :(得分:1)

您可以使用LIMIT获取最后修改的条目:

SELECT * 
FROM weather, cities 
WHERE weather.cities_plz = cities.plz
ORDER BY modified DESC
LIMIT 1;

您想要每个城市的最后一个条目:

SELECT DISTINCT * 
FROM weather, cities 
WHERE weather.cities_plz = cities.plz
    AND modified = (SELECT MAX(modified) FROM weather WHERE weather.cities_plz = plz)

答案 1 :(得分:0)

试试这个:

SELECT * FROM `weather`, `cities` WHERE `weather`.`cities_plz` = `cities`.`plz`
AND `modified` = (SELECT MAX(modified) FROM `weather` WHERE `cities_plz` = `cities_plz`) ORDER BY `modified` DESC;

答案 2 :(得分:0)

您可能希望在查询中添加不同的内容。

SELECT DISTINCT示例: https://www.w3schools.com/sql/sql_distinct.asp

答案 3 :(得分:0)

您可以使用 DISTINCT 关键字来避免重复的行。

来自MySQL文档 https://dev.mysql.com/doc/refman/5.7/en/distinct-optimization.html

答案 4 :(得分:0)

您必须为此

编写子查询
aaa bbb ccc: [DDD] efg oi    
aaa bbb ccc: lll [DDD] efg oo    
aaa bbb ccc: [DDD]