MyStream
MyStream

Reputation: 2553

Select previous record with multiple conditions in mysql

This one's been tricky to quantify, so I may not have this question worded properly first time around.

I have a table following a format similar to this:

| id | other_id | timestamp  |
|  1 |        1 | 2012-01-01 |
|  2 |        1 | 2012-01-02 |
|  3 |        2 | 2012-01-02 |

What I am attempting to do is, given the record with 'id' 2, and similar records, for which the 'id' column value is known and is unique and the 'other_id' is known corresponding with it, how do I find, for each, the 'id' of the record having the same 'other_id' but the first lower 'id' than the one I already know.

E.g.

$arrKnownIds = array (
 0 => array('id'=>2,'other_id'=>1),
 1 => array('id'=>3,'other_id'=>2)
);

With this info, I'd like to run a query such that this results:

while($row = mysql_fetch_assoc($result)) {
 $arrPreviousIds[$row['other_id']] = $row['id'];
 // having in this case values of:
 // $row['other_id'] = 2;
 // $row['id'] = 1;
}

I can't quite work out if I need to tackle this using UNION, multiple php query statements or if there's another way.

Any thoughts on how to tackle this one are greatly appreciated.

Thanks :)

Edit - The original query takes the following form:

SELECT DISTINCT(`other_id`), MAX(`id`), MAX(`timestamp`)
FROM `event`
GROUP BY `other_id`
ORDER BY `id` DESC, `other_id` ASC
LIMIT 0, 10

// This is intended to get the last 10 unique events and find when they occurred.

// From this, I then try to find when they previously occurred.

Upvotes: 0

Views: 854

Answers (1)

user1191247
user1191247

Reputation: 12973

How about this?

SELECT t1.id, (SELECT id
               FROM tbl t2
               WHERE t2.other_id = t1.other_id
               AND t2.id < t1.id
               ORDER BY t2.id DESC
               LIMIT 1)
FROM tbl t1
WHERE t1.id IN (1,2,3)

There are more efficient ways of doing this if you will be dealing with large result sets. Can you explain exactly how you will be using this query?

UPDATE - based on addition of existing query to question here is an updated query to combine the two -

SELECT tmp.*, (SELECT `timestamp`
               FROM `event`
               WHERE `event`.`other_id` = `tmp`.`other_id`
               AND `event`.`id` < `tmp`.`id`
               ORDER BY `event`.`id` DESC
               LIMIT 1) AS `prev_timestamp`
FROM (
    SELECT `other_id`, MAX(`id`) AS `id`, MAX(`timestamp`) AS `timestamp`
    FROM `event`
    GROUP BY `other_id`
    ORDER BY `id` DESC, `other_id` ASC
    LIMIT 0, 10
) tmp

I have not tried this but it should give the desired result.

Upvotes: 1

Related Questions