MySQL LEFT JOIN RAND() - 奇怪的行为?或者我做错了什么?

时间:2011-01-24 14:41:53

标签: sql mysql

我几乎肯定我做错了什么,但我无法弄明白到底是什么。

查询运行良好几次,有时会无缘无故返回空aff_affiliatelink。 如果我从第一个JOIN中删除RAND(),一切正常,但是,我需要一个随机的联盟... 关于可能导致这种情况的任何想法?

编辑:刚注意到一些事情,失败的aff_affiliatelink的game_software总是“2”。不知道它是否有任何联系,但它可能有助于理解错误。

这是我的问题:

   SELECT game_software,
          aff_affiliatelink
     FROM games g     
LEFT JOIN (SELECT asoft_affiliateid,asoft_softwareid 
             FROM affiliates_software 
         ORDER BY RAND() ) aff_soft ON aff_soft.asoft_softwareid =g.game_software    
LEFT JOIN (SELECT aff_id, 
                  aff_affiliatelink,
                  aff_description,
                  aff_bonus,
                  aff_title,
                  aff_image,
                  aff_imagealt,
                  aff_banner,
                  aff_banneralt 
             FROM affiliates 
            WHERE aff_isactive = 1) aff ON aff_id=aff_soft.asoft_affiliateid     
 GROUP BY game_id 
 ORDER BY game_releasedate DESC

编辑:将第二个LEFT JOIN更改为INNER JOIN后, 它似乎工作,但我不确定这是正确的方式.... 如果有人有另一个想法,请告诉我,我将保持这个问题,直到我得到一个体面的答案。

3 个答案:

答案 0 :(得分:1)

问题是您稍后要重新排序查询。如果您尝试从随机会员中获取单个项目,则应在LIMIT 1之后添加ORDER BY RAND()。否则,订单只会减慢您的查询速度,因为它将在稍后被外部订单覆盖。

哦,你应该查看关于ORDER BY RAND() ...

this blog post

答案 1 :(得分:1)

SELECT  game_software, aff_affiliatelink
FROM    (
        SELECT  game_software, game_releasedate
                (
                SELECT  asoft_affiliateid
                FROM    affiliates_software afs
                WHERE   afs.afost_softwareid = g.game_software
                ORDER BY
                        RAND()
                LIMIT 1
                ) AS asoft_affiliateid
        FROM    games g
        ) asd
LEFT JOIN
        affiliates a
ON      a.aff_id = asd.asoft_affiliateid
        AND a.aff_isactive = 1
ORDER BY
        game_releasedate DESC

答案 2 :(得分:0)

经过一些测试后,解决方案是将第二个左连接更改为内连接。 谢谢你的帮助。

SELECT game_id,gtype_imagefolder,game_isactive,game_title,game_description,game_image,game_imagealt,game_content,game_alias,game_software,game_flashlink,game_metatitle,game_metakeywords,game_metadescription,game_h1title,game_h1content,game_h2title,game_h2content,aff_affiliatelink,aff_description,aff_bonus,aff_id,aff_title,aff_image,aff_imagealt,aff_banner,aff_banneralt  
FROM games g 
LEFT JOIN (SELECT asoft_affiliateid,asoft_softwareid 
      FROM affiliates_software 
      ORDER BY RAND() ) aff_soft 
ON g.game_software=aff_soft.asoft_softwareid 
INNER JOIN (SELECT aff_id,aff_affiliatelink,aff_description,aff_bonus,aff_title,aff_image,aff_imagealt,aff_banner,aff_banneralt 
            FROM affiliates 
            WHERE aff_isactive=1) aff 
ON aff_id=asoft_affiliateid 
LEFT JOIN (SELECT gtype_imagefolder,gtype_id FROM games_type) gt ON game_type=gtype_id 
WHERE game_type=1 

GROUP BY game_id ORDER BY game_releasedate DESC