How do I change this query to be a left join?

Discussion in 'Databases' started by GeoffreyF67, May 9, 2007.

  1. #1
    I've got the query below that I'm using and it's REALLY slow. I've recently learned that a left join would be a lot faster but I don't know how to convert it into a left join.

    Anyone have any ideas?

    
                $PingTrackerSQL = "Select KeywordID from LG.PingTracker where DatePinged > Date_Sub(CurDate(), Interval 7 Day)";
    
    $RKSQL = "select ID from B.Keywords
                                      where RootKeywordID = $RootKeywordID
                                        and ID not in ($PingTrackerSQL)
                                        order by rand() limit 1";
    Code (markup):
     
    GeoffreyF67, May 9, 2007 IP
  2. kjewat

    kjewat Active Member

    Messages:
    149
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    53
    #2
    It looks like you can do a regular inner join and set criteria to <= instead of NOT IN >

    Something like this:
    
    $RKSQL="select ID from B.Keywords KW
    INNER JOIN LG.PingTracker PT ON KW.ID=PT.RootKeywordID
    where KW.RootKeywordID = $RootKeywordID
    and PT.DatePinged <= Date_Sub(CurDate(), Interval 7 Day)
    order by rand() limit 1"
    
    
    Code (markup):
     
    kjewat, May 9, 2007 IP
  3. SoKickIt

    SoKickIt Active Member

    Messages:
    305
    Likes Received:
    30
    Best Answers:
    0
    Trophy Points:
    70
    #3
    "order by rand()" is what makes your query slow... that and probably a lack of "DatePinged" index...
     
    SoKickIt, May 9, 2007 IP
  4. gibex

    gibex Active Member

    Messages:
    1,060
    Likes Received:
    21
    Best Answers:
    0
    Trophy Points:
    95
    #4
    left join won't be faster if you don't try to optimize ORDER BY
     
    gibex, May 12, 2007 IP