Skip to content
Advertisement

Limit the results returned by MySQL join to 1

I’m doing a JOIN on two tables and the right side has multiple results for the ON clause: e.ID = ti.event_id. How do I limit the results returned by the join to 1? Sort of like LIMIT 1

events_detail tbl:

ID | event_code
---------------
1  | 123-abc
2  | 234-bcd
3  | 345-cde

events_start_end tbl:

id | event_id | start_time | end_time
-------------------------------------
1  | 1        | 12:00      | 17:00
2  | 1        | 13:00      | 15:00
3  | 2        | 12:00      | 15:00
4  | 3        | 07:00      | 10:00
5  | 3        | 08:00      | 11:00

Current query:

SELECT e.ID, e.event_code, ti.start_time, ti.end_time 
FROM events_detail AS e 
LEFT JOIN events_start_end AS ti 
  ON e.ID = ti.event_id 
WHERE e.event_status = 'A';

Actual results:

ID | event_code | start_time | end_time
---------------------------------------
1  | 123-abc    | 12:00      | 17:00
1  | 123-abc    | 13:00      | 15:00
2  | 234-bcd    | 12:00      | 15:00
3  | 345-cde    | 07:00      | 10:00
3  | 345-cde    | 08:00      | 11:00

Preferred results:

ID | event_code | start_time | end_time
---------------------------------------
1  | 123-abc    | 12:00      | 17:00
2  | 234-bcd    | 12:00      | 15:00
3  | 345-cde    | 07:00      | 10:00

Advertisement

Answer

Use ROW_NUMBER():

SELECT e.*
FROM (SELECT e.ID, e.event_code, ti.start_time, ti.end_time,
             ROW_NUMBER() OVER (PARTITION BY e.event_code ORDER BY t1.start_time) as seqnum 
      FROM events_detail e LEFT JOIN
           events_start_end ti 
           ON e.ID = ti.event_id 
      WHERE e.event_status = 'A'
     ) e
WHERE seqnum = 1;
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement