Combining 2 mysql statements into 1

Discussion in 'Databases' started by sc_king, Dec 20, 2009.

  1. #1
    I have 2 statements which I want to join into 1.

    First statement grabs the actors ratings and details.
    Second statement grabs the number of videos each actor appears from a certain date.

    select actors.*, actor_ratings.* from actors, actor_ratings where actors.id = actor_ratings.actor_id limit $perpage offset $start

    select actor_id, count(*) as total_videos from videos, video_actors where date_added < '$date' and videos.id = video_actors.video_id group by actor_id

    Tried some inner joins but the query seems much slower. What's the best way to join these 2 tables together based on actor id?

    Thank you.
     
    Last edited: Dec 20, 2009
    sc_king, Dec 20, 2009 IP
  2. markzero

    markzero Peon

    Messages:
    133
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I guess you are looking for union operator ;)
     
    markzero, Dec 20, 2009 IP
  3. sc_king

    sc_king Peon

    Messages:
    29
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I believe union is used for tables with same type of information?
    I could be wrong

    I need the two tables joined by actor id that way I have the actor's details and the number of videos he/she is in
     
    sc_king, Dec 20, 2009 IP
  4. sc_king

    sc_king Peon

    Messages:
    29
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    I think I got it.

    select * from (select actor_id, count(*) as total_videos from videos, video_actors where videos.date_added < '$date' and videos.id = video_actors.video_id group by actor_id) as videos_per_actor RIGHT JOIN actors ON actors.id = videos_per_actor.actor_id INNER JOIN actor_ratings ON actor_ratings.actor_id = actors.id limit $perpage offset $start

    0.07 seconds on 50k tables.

    But when I add "order by name" it adds an extra second or two.

    select * from (select actor_id, count(*) as total_videos from videos, video_actors where videos.date_added < '$date' and videos.id = video_actors.video_id group by actor_id) as videos_per_actor RIGHT JOIN actors ON actors.id = videos_per_actor.actor_id LEFT JOIN actor_ratings ON actor_ratings.actor_id = actors.id order by name limit $perpage offset $start

    A normal order by name on the table takes .07 but it adds 1 or 2 seconds when it's placed with the joins. Why is this the case?
     
    Last edited: Dec 20, 2009
    sc_king, Dec 20, 2009 IP