MySQL display rows from 2 tables with most recent data in table 2 -
i have 2 tables use, want display result depending on recent data in table2 owner in table1 = 'ownera': table1 :
# id, name, owner ________________________________________________ 19782, device1, ownera 19783, device8, ownerb 19784, device2, ownera 19785, device3, ownera
table2 :
# 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
what want in output :
# 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
this tried, :
select nasid, sim, max(timestamp) table1 t1,table2 t2 table1.owner='ownera' , t2.timestamp = (select max(t2_2.timestamp) table2 t2_2 t2.sim=t2_2.sim)
this show create : table1:
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
table2:
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
generally generate data set max values , unique key join base set containing other data need.
select t1.name, t2.nasid, t2.sim, t2.timestamp table1 t1 inner join table2 t2 on t1.id = t2.nasid inner join (select max(timestamp) mt, nasid table2 group nasid) on a.mt = t2.timestamp , a.nasid = t2.nasid t1.owner = 'ownera'
well lets go original query...
i think had wrong there sim should nasid. sim doens't appear key table. nasid , timestamp based on data presented generate unique key. on , you're missing join between t1 , t2.
select name, nasid, sim, timestamp table1 t1,table2 t2 table1.owner='ownera' , t1.id = t2.nasid , t2.timestamp = (select max(t2_2.timestamp) table2 t2_2 t2.nasid=t2_2.nasid)
Comments
Post a Comment