views:

30

answers:

1
+1  Q: 

Need MySQL help

Hey folks :)

I'm having a little trouble with an sql query. Which is why I hope some of you will be able to help me.

I've got an query that selects the latest entry from each relational id but i want to select the latest where the status is different. The table looks like this.

+-----------+-------------+------+-----+-------------------+----------------+
| Field     | Type        | Null | Key | Default           | Extra          |
+-----------+-------------+------+-----+-------------------+----------------+
| id        | int(11)     | NO   | PRI | NULL              | auto_increment |
| kid_id    | int(11)     | NO   |     | NULL              |                |
| status    | varchar(50) | NO   |     | NULL              |                |
| timestamp | timestamp   | NO   |     | CURRENT_TIMESTAMP |                |
+-----------+-------------+------+-----+-------------------+----------------+

And my current query looks like this.

SELECT * 
            FROM (
                SELECT * 
                FROM actions 
                AS a
                WHERE date(timestamp) = curdate() 
                AND timestamp = (
                    SELECT max(timestamp) 
                    FROM actions 
                    AS b
                    WHERE a.kid_id = b.kid_id
                    )
                )
            AS c
            ORDER BY kid_id

And the result looks like this:

id  kid_id  status  timestamp
54  1   Kommet  2010-09-15 00:14:51
57  2   Gået    2010-09-15 00:17:58
56  3   Kommet  2010-09-15 00:15:00

The problem is that where kid_id equals 2 I would like to see the latest entry where status = "Kommet"....

I want the 2 newest records from each kid. The first record where status = "Kommet" and the second where status = "Gået"

In advance thank you very much for your help... It's really appreciated :)

A: 

If you're not to bothered about getting the id, then you could run the following:

SELECT kid_id, status, MAX(`timestamp`) as `timestamp`
FROM actions
WHERE DATE(`timestamp`) = CURDATE()
GROUP BY kid_id, status

If you needed the id, tou couldn't just add to the SELECT list though, as the GROUP BY will pull one of the matching ids to display here, not neccessarily the one that matches the MAX(timestamp).

Gus
Thank you very much this helped me alot. I did a couple of small modifications but basicly this solved my problem:)
nickifrandsen