I want to select the best result of each member from the mysql table, for a given discipline. (if there are entries with the same value, the entries with the lowest event start date should be taken)
DDLs:
 CREATE TABLE `results` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `discipline` int(11) NOT NULL,
      `member` int(11) DEFAULT '0',
      `event` int(11) DEFAULT '0',
      `value` int(11) DEFAULT '0',
      PRIMARY KEY (`id`),
      UNIQUE KEY `member_2` (`member`,`discipline`,`event`)
     );
     INSERT INTO results VALUES
     (1,1,2,4,10),
     (2,1,1,4, 8),
     (3,1,2,5, 9),
     (4,2,3,5, 9),
     (5,1,2,6,11),
     (6,1,2,7,11),
     (7,1,2,1,11),
     (8,1,2,3, 7);
CREATE TABLE `events` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `startDate` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
);
INSERT INTO events VALUES
(1 ,'Not in scope','2012-05-23'),
(3 ,'Test 0', '2014-05-09'),
(4 ,'Test 1', '2014-05-10'),
(5 ,'Test 2', '2014-05-11'),
(6 ,'Test 3', '2014-05-12'),
(7 ,'Test 4', '2014-05-13');
SELECT * FROM results;
+----+------------+--------+-------+-------+
| id | discipline | member | event | value |
+----+------------+--------+-------+-------+
|  1 |          1 |      2 |     4 |    10 |
|  2 |          1 |      1 |     4 |     8 |
|  3 |          1 |      2 |     5 |     9 |
|  4 |          2 |      3 |     5 |     9 |
|  5 |          1 |      2 |     6 |    11 |
|  6 |          1 |      2 |     7 |    11 |
|  7 |          1 |      2 |     1 |    11 |
|  8 |          1 |      2 |     3 |     7 |
+----+------------+--------+-------+-------+
SELECT * FROM events;
+----+--------------+---------------------+
| id | name         | startDate           |
+----+--------------+---------------------+
|  1 | Not in scope | 2012-05-23 00:00:00 |
|  3 | Test 0       | 2014-05-09 00:00:00 |
|  4 | Test 1       | 2014-05-10 00:00:00 |
|  5 | Test 2       | 2014-05-11 00:00:00 |
|  6 | Test 3       | 2014-05-12 00:00:00 |
|  7 | Test 4       | 2014-05-13 00:00:00 |
+----+--------------+---------------------+
Result should be:
+---------+------------+--------+-------+-------+
| id      | discipline | member | event | value |
+---------+------------+--------+-------+-------+
|       3 |          1 |      1 |     4 |     8 |
|       5 |          1 |      2 |     6 |    11 |
+---------+------------+--------+-------+-------+
My first approach was to group by member id, but it's not that easy. So I tried a lot of different approaches from the web and from my colleages.
The last one was:
select res.* 
from `results` as res
join (select id, max(value) 
      from results
      join events on results.event = events.id 
      where discipline = 1
      events.name like 'Test%' 
      Group by id
      Order by events.startDate ASC) as tmpRes 
on res.id = tmpRes.id
group by member
order by value DESC
But the result in this example would be a random result id for member 2.
 
     
    