MySQL - Exclude rows from Select based on duplication of two columns

Posted by Carson C. on Stack Overflow See other posts from Stack Overflow or by Carson C.
Published on 2011-01-07T18:47:17Z Indexed on 2011/01/07 18:53 UTC
Read the original article Hit count: 120

Filed under:
|

I am attempting to narrow results of an existing complex query based on conditional matches on multiple columns within the returned data set. I'll attempt to simplify the data as much as possible here.

Assume that the following table structure represents the data that my existing complex query has already selected (here ordered by date):

+----+-----------+------+------------+
| id | remote_id | type | date       |
+----+-----------+------+------------+
|  1 |         1 | A    | 2011-01-01 |
|  3 |         1 | A    | 2011-01-07 |
|  5 |         1 | B    | 2011-01-07 |
|  4 |         1 | A    | 2011-05-01 |
+----+-----------+------+------------+

I need to select from that data set based on the following criteria:

  • If the pairing of remote_id and type is unique to the set, return the row always
  • If the pairing of remote_id and type is not unique to the set, take the following action:
    • Of the sets of rows for which the pairing of remote_id and type are not unique, return only the single row for which date is greatest and still less than or equal to now.

So, if today is 2010-01-10, I'd like the data set returned to be:

+----+-----------+------+------------+
| id | remote_id | type | date       |
+----+-----------+------+------------+
|  3 |         1 | A    | 2011-01-07 |
|  5 |         1 | B    | 2011-01-07 |
+----+-----------+------+------------+

For some reason I'm having no luck wrapping my head around this one. I suspect the answer lies in good application of group_by, but I just can't grasp it. Any help is greatly appreciated!

© Stack Overflow or respective owner

Related posts about mysql

Related posts about mysql-query