multiple child for one parent in mysql

Discussion in 'MySQL' started by asmon, Jul 22, 2009.

  1. #1
    i have a table of users and a table of activities.
    each user can be related to a few activities

    when i enter an activity, i need display the user list and vice versa
    how can i make that connection?
    if i seperate the ids by commas, i won't be able to make a selection by id
     
    asmon, Jul 22, 2009 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    You would use 2 tables:

    user_table
    user_id
    other_columns

    activities_table
    activity_id
    user_id
    activity_name

    You can then add as many activities as you want for each user. You can do a Join to connect the activities of each user.
     
    jestep, Jul 22, 2009 IP
  3. asmon

    asmon Member

    Messages:
    56
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #3
    i need many users to be related to the same activity id...
     
    asmon, Jul 22, 2009 IP
  4. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #4
    I see. It would be a little different then.

    activities_table
    activity_id
    activity_name

    user_table
    user_id
    other_columns

    user_activities
    ua_id
    activity_id
    user_id
     
    jestep, Jul 22, 2009 IP
  5. asmon

    asmon Member

    Messages:
    56
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #5
    thought there might be an easier way, without using 3 tables.
    thank you.
     
    asmon, Jul 22, 2009 IP
  6. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #6
    You can use a JOIN to get this information very easily. It looks more complicated, but storing as a csv prevents MySQL from being able to use the data.

    To get activities:
    SELECT activities_table.activity_name FROM activities_table
    LEFT JOIN user_activities ON activities_table.activity_id = user_activities.activity_id
    WHERE user_activities.user_id = '';

    To get users:
    SELECT user_table.user_name FROM user_table
    LEFT JOIN user_activities ON user_table.user_id = user_activities.user_id
    WHERE user_activities.activity_id = '';
     
    jestep, Jul 22, 2009 IP