我有2個表要使用,我希望顯示結果取決於Table2中的所有者在table1 ='ownerA'中的最近數據: 表1:MySQL顯示來自表2中最近數據的2個表中的行
# id, name, owner
________________________________________________
19782, device1, ownerA
19783, device8, ownerB
19784, device2, ownerA
19785, device3, ownerA
表2:
# nasid, sim, timestamp
_______________________________________
19782, 0, 2015-12-08 15:34:27
19782, 0, 2015-12-08 15:34:33
19772, 0, 2015-12-08 15:34:39
19752, 0, 2015-12-08 15:34:45
19783, 0, 2015-12-08 15:34:50
19712, 0, 2015-12-08 15:34:56
19783, 0, 2015-12-08 15:35:02
19782, 0, 2015-12-08 15:35:07
19784, 0, 2015-12-08 15:35:13
19784, 0, 2015-12-08 15:35:20
我想在輸出得到什麼:
# name, nasid, sim, timestamp
_______________________________________
device8, 19783, 0, 2015-12-08 15:35:02
device1, 19782, 0, 2015-12-08 15:35:07
device2, 19784, 0, 2015-12-08 15:35:20
這是我試過了,:
select nasid, sim, MAX(timestamp)
from Table1 T1,Table2 T2
where
Table1.owner='ownerA'
and
T2.timestamp = (SELECT MAX(T2_2.timestamp)
FROM Table2 T2_2
WHERE T2.sim=T2_2.sim)
這是我SHOW CREATE: 表1:
CREATE TABLE `Table1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(64) COLLATE latin1_general_ci DEFAULT NULL,
`owner` varchar(128) COLLATE latin1_general_ci DEFAULT '',
UNIQUE KEY `name` (`name`),
KEY `id` (`id`),
KEY `owner` (`owner`),
) ENGINE=InnoDB AUTO_INCREMENT=26696 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci
表2:
CREATE TABLE `Table2` (
`nasid` int(11) DEFAULT NULL,
`sim` char(20) COLLATE latin1_general_ci DEFAULT NULL,
`timestamp` datetime DEFAULT NULL,
KEY `nasid` (`nasid`),
KEY `timestamp` (`timestamp`),
KEY `sim` (`sim`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci
你想最近的時間戳或全部? – WillardSolutions
@EatPeanutButter,每個設備的最新版本 – user2997418
爲什麼device8在您的預期輸出中,如果擁有者是'B'?你的where子句擁有ownerA? – xQbert