E
E
enchikiben2016-01-13 12:45:50
MySQL
enchikiben, 2016-01-13 12:45:50

How to select recent entries?

Good afternoon!
There is a table (group):
id name
1 aaa
2 bbb
3 cccc
and there is a table (stat) of statistics for these records
id group_id date value
1 1 2015-12-12 1
2 1 2015-12-15 5
3 2 2015-12- 11 3
4 3 2015-12-12 2
5 1 2015-12-14 1
6 2 2015-12-18 3
you need to select statistics for the last date with one query, you should get something like:
name date value
aaa 2015-12-15 5
bbb 2015-12-18 3
ccc 2015-12-12 2
Is this possible?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
P
Peter, 2016-01-13
@EnChikiben

select g.name, st.date, st.value from group g
inner join (select group_id, max(date) md from stat group by group_id) s on s.group_id = g.id
inner join stat st on st.group_id = g.id and st.date = s.md

K
Konstantin B., 2016-01-13
@Kostik_1993

SELECT * FROM stat, group WHERE group.id = stat.group_id ORDER BY date DESC LIMIT 5

N
nozzy, 2016-01-13
@nozzy

select 
t1.name,
t2.d,
t2.value
from group t1
inner join
(
  select
  group_id,
  value,
  max(date) as d
  from stat
  group by group_id,  value
  ) t2 on t2.group_id = t1.id

R
Rsa97, 2016-01-13
@Rsa97

SELECT `g`.`name`, `s`.`date`, `s`.`value`
    FROM (
        SELECT `group_id`, MAX(`date`) AS `date`
        FROM `stat`
        GROUP BY `group_id`
    ) AS `d`
    JOIN `stat` AS `s` ON `s`.`date` = `d`.`date` AND `s`.`group_id` = `d`.`group_id`
    JOIN `group` AS `g` ON `g`.`id` = `d`.`group_id`

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question