cfree
cfree

Reputation: 333

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

Upvotes: 0

Views: 48

Answers (2)

cfree
cfree

Reputation: 333

I ended up solving this by using a subquery:

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 `ti`.`id` = (
        SELECT `id` 
        FROM `events_start_end` 
        WHERE `events_start_end`.`event_id` = `e`.`ID` 
        LIMIT 1
    ) 
WHERE `e`.`event_status` = 'A'

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1271003

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;

Upvotes: 2

Related Questions