atp*_*atp 45 mysql group-by sql-order-by
我有下表:
    id       time      text      otheridentifier
    -------------------------------------------
    1        6         apple     4
    2        7         orange    4
    3        8         banana    3
    4        9         pear      3
    5        10        grape     2
我想要做的是选择3个最近的记录(按时间desc),其中otheridentifiers是不同的.所以在这种情况下,结果将是id's:5,4和2.
id将跳过= 3,因为最近的记录具有相同的otheridentifier字段.
这是我试图做的事情:
SELECT * FROM `table` GROUP BY (`otheridentifier`) ORDER BY `time` DESC LIMIT 3
然而,我最终得到的行id= 5,3,和1而不是5,4,2按预期方式.
有人能告诉我为什么这个查询不会返回我的预期吗?我尝试将ORDER BY更改为ASC,但这只是将返回的行重新排列为1,3,5.
cha*_*aos 34
它不会返回您期望的内容,因为分组在排序之前发生,正如SQL语句中子句的位置所反映的那样.不幸的是,你必须得到更好的方法来获得你想要的行.试试这个:
SELECT *
FROM `table`
WHERE `id` = (
    SELECT `id`
    FROM `table` as `alt`
    WHERE `alt`.`otheridentifier` = `table`.`otheridentifier`
    ORDER BY `time` DESC
    LIMIT 1
)
ORDER BY `time` DESC
LIMIT 3
And*_*mar 18
您可以将表连接到自身以过滤每个最后一个条目otheridentifier,然后获取前三行:
SELECT last.*
FROM `table` last
LEFT JOIN `table` prev 
    ON prev.`otheridentifier` = last.`otheridentifier`
    AND prev.`time` < last.`time`
WHERE prev.`id` is null
ORDER BY last.`time` DESC 
LIMIT 3
| 归档时间: | 
 | 
| 查看次数: | 35896 次 | 
| 最近记录: |