問題:
如何檢索最新行的PID使用使用了() 和GROUP 的MySQL 查詢對錶中的每個RID BY?
範例資料:
CREATE TABLE theTable ( `pid` INT UNSIGNED PRIMARY KEY AUTO_INCREMENT, `timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, `cost` INT UNSIGNED NOT NULL, `rid` INT NOT NULL, ) Engine=InnoDB; INSERT INTO theTable (`pid`, `timestamp`, `cost`, `rid`) VALUES (1, '2011-04-14 01:05:07', 1122, 1), (2, '2011-04-14 00:05:07', 2233, 1), (3, '2011-04-14 01:05:41', 4455, 2), (4, '2011-04-14 01:01:11', 5566, 2), (5, '2011-04-14 01:06:06', 345, 1), (6, '2011-04-13 22:06:06', 543, 2), (7, '2011-04-14 01:14:14', 5435, 3), (8, '2011-04-14 01:10:13', 6767, 3) ;
期望結果:
pid | MAX(timestamp) | rid ----------------------------------- 5 | 2011-04-14 01:06:06 | 1 3 | 2011-04-14 01:05:41 | 2 7 | 2011-04-14 01:14:14 | 3
🎜>
SELECT MAX(timestamp),rid,pid FROM theTable GROUP BY rid
正確查詢:
要檢索每個RID 的最新行的PID,可以使用以下命令查詢:SELECT pid, MAX(timestamp) AS latest_timestamp, rid FROM theTable GROUP BY rid HAVING latest_timestamp = MAX(timestamp)
以上是如何使用 MAX() 和 GROUP BY 取得 MySQL 中每個 RID 的最新 PID?的詳細內容。更多資訊請關注PHP中文網其他相關文章!