Search code examples
mysqlsqlgroupwise-maximum

How to return only one row from the right-most table using mysql join


I have two tables. I want to join them in a way that only one record(the first matched record) in the right table is returned for the record in the left most table. the two tables have a one to many relationship. here are the tables below:

events table :

      -------------------------------------------------------------
      | event_id | event_name |event_details|event_venue|dress_code|
      -------------------------------------------------------------
      | 1        | club 92    |blah blahblah|somewhere  |something |
      | 2        | graduation |blah blahblah|somewhere  |something |
      | 3        | party      |blah blahblah|somewhere  |something |
      --------------------------------------------------------------

tickets table :

      -----------------------------------------------
      |ticket_id | ticket_name  | price | event_id  |
      -----------------------------------------------
      | 1        | first        |   0   |   1       |
      | 2        | second       |   10  |   1       |
      | 3        | third        |   100 |   1       |
      | 4        | fourth       |   10  |   2       |
      | 5        | fifth        |   200 |   2       |
      -----------------------------------------------

is this possible using join ? i'm open to any other ideas


Solution

  • You can't do this just with a join. Here is one method:

    select e.*, t.*
    from events e join
         tickets t
         on e.event_id = t.event_id
    where t.id = (select min(t2.id)
                  from tickets t2
                  where t2.event_id = t.event_id
                 );