Reputation: 343
I have the following query.
SELECT DISTINCT tbl_event_entries.race_nbr,
tbl_event_entries.class_id,
tbl_event_entries.racer_id,
tbl_event_entries.heat_position,
tbl_event_classes.combine
FROM tbl_event_entries
LEFT JOIN tbl_event_classes
ON tbl_event_entries.class_id = tbl_event_classes.class_id
WHERE tbl_event_entries.event_id = :event_id
ORDER BY tbl_event_entries.race_nbr, tbl_event_entries.heat_position
The data that this is in this query is :
event_class_id event_id class_id combine
822 20160706MAS577d098260173 1 2
823 20160706MAS577d098260173 2 8888
entry_id event_id racer_id class_id
8318 20160706MAS577d098260173 238 1
8319 20160706MAS577d098260173 1184 2
The output that I get from this query:
race_nbr class_id racer_id heat_position combine
1 1 238 1 2
1 1 238 1 NULL
2 2 1184 1 8888
2 2 1184 1 NULL
I can limit the query to not show "NULL" in combined, but I don't always have data in that field. But, I should never see duplicated rows like this.
I should see just two rows:
race_nbr class_id racer_id heat_position combine
1 1 238 1 2
2 2 1184 1 8888
Can anyone see the error?
I have tried LEFT JOIN, JOIN and a few different changes with the fields. Not seeing why this is returning the invalid data..
Upvotes: 0
Views: 86
Reputation: 33945
Answer: Use aggregation...
SELECT e.race_nbr
, e.class_id
, e.racer_id
, e.heat_position
, MAX(c.combine) combine
FROM tbl_event_entries e
LEFT
JOIN tbl_event_classes c
ON c.class_id = e.class_id
WHERE e.event_id = :event_id
GROUP
BY e.race_nbr
, e.class_id
, e.racer_id
, e.heat_position
ORDER
BY e.race_nbr
, e.heat_position
Upvotes: 1