php - mySQL group records with latest entry from child table -



php - mySQL group records with latest entry from child table -

i have 3 tables office, computer , maintain. office list of offices, computers belongs office has many maintains.

i want left bring together tables latest entry maintain table. the code below works grouping oldest entry in maintain.

select `computer`.`id`, `computer`.`control`, `computer`.`operator`, `computer`.`datepurchased`, `computer`.`type`, `computer`.`property`, `computer`.`printer`, `computer`.`scanner`, `computer`.`osx`, `computer`.`applications`, `computer`.`licence`, `computer`.`isstandalone`, `computer`.`isinternet`, `computer`.`isnetwork`, `computer`.`generalstatus`, `computer`.`ip_address`, `computer`.`mac_address`, `computer`.`user_id`, `computer`.`office_id`, `computer`.`created`, `computer`.`modified`, `computer`.`deleted`, `office`.`id`, `office`.`description`, `office`.`main_office`, `maintain`.`id`, `maintain`.`dateencoded`, `maintain`.`findings`, `maintain`.`checkedby`, `maintain`.`remarks`, `maintain`.`computer_id`, `maintain`.`created`, `maintain`.`modified`, `maintain`.`user_id` `computers`.`computer` `computer` left bring together `computers`.`office` `office` on (`office`.`id` = `computer`.`office_id`) left bring together `computers`.`maintain` `maintain` on (`computer`.`id` = `maintain`.`computer_id`) left bring together (select max(dateencoded) maxdate, findings maintain grouping computer_id) `p2` on (`maintain`.`dateencoded` = `p2`.`maxdate`) `office`.`main_office` '%cvph mon%' grouping `computer`.`id` order `office`.`description` asc

sample

office 1 aaaa 2 bbbb computer id name office_id 1 cp1 1 2 cp2 1 3 cp3 2 maintain id description date computer_id 1 prepare 06/20/2014 1 2 prepare 06/11/2014 1 3 prepare 06/12/2014 2 4 prepare 06/15/2014 2 result if query on computer=cp1 should office computer_name maintain_desc date aaa cp1 prepare 06/20/2014 <- latest entry in maintain

you can so

select `c`.`id`, `c`.`name`, `c`.`office_id` , `o`.`name` office_name, `m`.`date`, `m`.`description` `computer` c left bring together `office` `o` on (`o`.`id` = `c`.`office_id`) left bring together `maintain` m on (`c`.`id` = `m`.`computer_id`) inner bring together (select computer_id,max(`date`) maxdate maintain grouping computer_id ) t on(m.`date`=t.maxdate , m.computer_id= t.computer_id) `c`.`name` ='cp1' ... more conditions demo

php mysql mysqli

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -