Query that selects the last line of each device?

0

I have 3 tables in my DB:

CREATE TABLE IF NOT EXISTS 'local' (
  'codigo' int(11) NOT NULL AUTO_INCREMENT,
  'IMEI' varchar(15) NOT NULL,
  'latitude' decimal(10,6) NOT NULL,
  'longitude' decimal(10,6) NOT NULL,
  'datetime' datetime NOT NULL,
  PRIMARY KEY ('codigo')
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2323 ;

CREATE TABLE IF NOT EXISTS 'dispositivos' (
  'codigo' int(11) NOT NULL AUTO_INCREMENT,
  'IMEI' varchar(15) NOT NULL,
  'client' int(11) NOT NULL,
  PRIMARY KEY ('codigo')
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

CREATE TABLE IF NOT EXISTS 'clientes' (
  'codigo' int(11) NOT NULL AUTO_INCREMENT,
  'numero_cliente' int(11) NOT NULL,
  'nome' varchar(50) NOT NULL,
  'login' varchar(20) NOT NULL,
  'password' varchar(20) NOT NULL,
  PRIMARY KEY ('codigo')
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

Customers have devices that send messages from their location (with the date of the device itself, so I do not sort the table by date).

All tables are sorted by field auto_increment .

I would like to know how to get the last line of the local table of each device for a given client.

For example:

Client 1000 has the devices:

  • 111222333444555
  • 222333444555666
  • 333444555666777

I want to get the last line of 111222333444555 , plus the last line of 222333444555666 and the last line of 333444555666777 .

    
asked by anonymous 18.07.2014 / 21:06

1 answer

2

I could not test the code, I did "head." See if it does what you want:

select l.*
from
(
select d.imei, max(l.codigo) cod_local
from clientes c
join dispositivos d on d.client = c.codigo
join local l on l.imei = d.imei
where c.codigo = :param_cod_cli
group by d.imei
) aux_tab
join local l on l.codigo = aux_tab.cod_local
    
18.07.2014 / 21:29