mysql - multiple - sql join group by
選擇3個最新記錄,其中一列的值不同 (6)
我有下表:
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),其他otheridentifier
是不同的。 所以在這種情況下,結果將是id
: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。
Andomar的答案可能是最好的,因為它不使用子查詢。
另一種方法:
select *
from `table` t1
where t1.`time` in (
select max(s2.`time`)
from `table` t2
group by t2.otheridentifier
)
它不會返回您期望的內容,因為分組在排序之前發生,正如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
您可以將表連接到自身以過濾每個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
我有類似的要求,但我有更高級的選擇標準。 使用其他一些答案,我無法得到我所需要的,但我發現你仍然可以在這之後進行GROUP BY和ORDER BY:
SELECT t.* FROM (SELECT * FROM table ORDER BY time DESC) t
GROUP BY t.otheridentifier
關於什麼
SELECT *, max(time) FROM `table` group by otheridentifier
SELECT * FROM table t1
WHERE t1.time =
(SELECT MAX(time) FROM table t2
WHERE t2.otheridentifier = t1.otheridentifier)