我有2个表要使用,我希望显示结果,具体取决于table2中所有者Table1 ='ownerA'中的最新数据: 表1:
# 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
答案 0 :(得分:1)
通常我会生成一个包含最大值和唯一键的数据集,然后将其简单地连接回包含我们需要的其他数据的基本集。
SELECT T1.name, T2.nasid, T2.sim, T2.timestamp
FROM Table1 T1
INNER JOIN table2 T2
on T1.ID = T2.nasid
INNER JOIN (SELECT max(timestamp) mt, nasid
FROM table2
GROUP BY nasid) A
on A.MT = T2.TimeStamp
and A.Nasid = T2.Nasid
WHERE T1.Owner = 'ownerA'
好吧,让我们回到原始查询...
我认为你所有的错误都是sim应该是无效的。因为sim dons似乎是表格的关键。只有基于所提供数据的nasid和时间戳才会生成唯一密钥。你和你错过了t1和t2之间的联接。
select name, nasid, sim, timestamp
from Table1 T1,Table2 T2
where Table1.owner='ownerA'
and T1.Id = t2.nasid
and T2.timestamp = (SELECT MAX(T2_2.timestamp)
FROM Table2 T2_2
WHERE T2.nasid=T2_2.nasid)
答案 1 :(得分:0)
经过很长一段时间,这就是让它更快的原因:
SELECT name, nasid, sim, max(timestamp)
FROM Table1, Table2
WHERE Owner = 'OwnerA'
and id = nasid
GROUP BY nasid