delimiter $$
CREATE TABLE `tbl_locate` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Locating` bit(1) DEFAULT NULL,
`MainPower` bit(1) DEFAULT NULL,
`Acc` bit(1) DEFAULT NULL,
`PowerOff` bit(1) DEFAULT NULL,
`Alarm` int(11) DEFAULT NULL,
`Speed` int(11) DEFAULT NULL,
`Direction` int(11) DEFAULT NULL,
`Latitude` double DEFAULT NULL,
`Longitude` double DEFAULT NULL,
`DateTime` datetime DEFAULT NULL,
`MainID` int(11) DEFAULT NULL,
`IOState` int(11) DEFAULT NULL,
`OilState` int(11) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1$$
SELECT * FROM tbl_locate WHERE DateTime=(SELECT MAX(`DateTime`) FROM tbl_locate WHERE MainID=1,2,3)
我想返回主id为1或2或3的最新行数据,
所以,需要返回3行最新日期时间
第1行是id 1最新日期时间
第二行是id 2最新日期时间
第三行是id 3最新日期时间
怎么做?
答案 0 :(得分:1)
SELECT *
FROM tbl_locate AS a
INNER JOIN
(
SELECT MainID, Max(DateTime) AS DateTime
FROM tbl_locate
GROUP BY MainID
) AS b
ON a.MainID = b.MainID
AND a.DateTime = b.DateTime
WHERE b.MainID in(1,2,3)
试试这个
答案 1 :(得分:0)
按DateTime订购,并获得前3行:
SELECT * FROM tbl_locate
ORDER BY DateTime LIMIT 3
答案 2 :(得分:0)
这应该有效:
SELECT *
FROM tbl_locate t
JOIN (SELECT Max(DateTime) MaxDateTime, MainId
FROM tbl_Locate
WHERE MainId IN (1,2,3)
GROUP BY MainId) t2
ON t.MainId = t2.MainId AND t.DateTime = t2.MaxDateTime
这应该返回3行,Main ID 1,2,3各一行及其对应的Max(DateTime)。但是,如果存在多个具有相同DateTime的行,则它将返回多个记录。
以下是小提琴示例:http://sqlfiddle.com/#!2/f2c49/1
如果存在多个具有相同日期的记录,您需要引入一个RANK以确保您只为每个MainId返回一条记录:
SELECT *
FROM (
SELECT
@rowNumber:= IF(@prevRow=t.MainId, @rowNumber:=@rowNumber+1, 1) rank,
t.* ,
@prevRow:=t.MainId
FROM tbl_locate t
JOIN (SELECT
Max(DateTime) MaxDateTime, MainId
FROM tbl_Locate
WHERE MainId IN (1,2,3)
GROUP BY MainId) t2
ON t.MainId = t2.MainId AND t.DateTime = t2.MaxDateTime
JOIN (SELECT @rowNumber:= 0) t3
) t
WHERE rank = 1;
答案 3 :(得分:0)
试试这个:
SELECT
T1.*
FROM tbl_locate T1
LEFT JOIN tbl_locate T2
ON T1.MainID = T2.MainID
AND T1.`DateTime` < T2.`DateTime`
WHERE T2.Id IS NULL
AND MainID IN (1,2,3)