Note that this method was published before it became clear that it should handle priority relationships. I leave it here for reference (see comments below). Mark @ Mark's answer for a solution that processes communications as necessary:
SELECT p.id, p.vehicle_id, p.filename, p.priority
FROM pics p
JOIN (
SELECT vehicle_id, MAX(priority) max_priority
FROM pics
GROUP BY vehicle_id
) sub_p ON (sub_p.vehicle_id = p.vehicle_id AND
sub_p.max_priority = p.priority)
GROUP BY p.vehicle_id;
This suggests that there cannot be priority relationships for the same thing vehicle_id.
Test case:
CREATE TABLE pics (id int, vehicle_id int, filename varchar(10), priority int);
INSERT INTO pics VALUES ('1', '45', 'a.jpg', '4');
INSERT INTO pics VALUES ('2', '45', 'b.jpg', '1');
INSERT INTO pics VALUES ('3', '56', 'f.jpg', '4');
INSERT INTO pics VALUES ('4', '67', 'cc.jpg', '4');
INSERT INTO pics VALUES ('5', '45', 'kt.jpg', '3');
INSERT INTO pics VALUES ('6', '67', 'gg.jpg', '1');
Result:
+------+------------+----------+----------+
| id | vehicle_id | filename | priority |
+------+------------+----------+----------+
| 1 | 45 | a.jpg | 4 |
| 3 | 56 | f.jpg | 4 |
| 4 | 67 | cc.jpg | 4 |
+------+------------+----------+----------+
3 rows in set (0.01 sec)
source
share