连接查询出错

时间:2011-10-11 10:48:04

标签: mysql

SELECT r.game, u.username, r.userid, r.points, u.format  
FROM ".TBL_RANKING." r 
    INNER JOIN ".TBL_USERS." u 
    ON u.id = r.userid
WHERE r.type = '1' AND r.game = 
            (SELECT name 
             FROM ".TBL_GAME." 
             WHERE active = '1' 
             ORDER BY rand() 
             LIMIT 1) 
     AND u.format = 
           (SELECT name 
            FROM ".TBL_FORMAT." 
        WHERE active = '1' 
            ORDER BY rand() LIMIT 1)
ORDER BY r.points DESC LIMIT 5

此查询无法正常工作。它选择的是奇数用户,有时甚至都没有。

查询应该: - 从游戏桌中选择一个随机游戏 - 从格式表中选择随机格式 - 选择在该游戏中排名的用户,但仅限于所选格式

因此,如果随机选择是FIFA 12 Xbox 360,它会发现所有来自格式类型为Xbox 360并且在FIFA 12上排名的用户。

表结构如下:

*tbl_ranking*
 id 
 userid 
 game 
 points 
 type

*tbl_users*
id
username
format

*tbl_game*
id
name

*tbl_format*
id 
name

有人能在这里看到问题吗?

1 个答案:

答案 0 :(得分:1)

尝试使用左连接

进行子查询
SELECT r.game, u.username, r.userid, r.points, u.format 
  FROM TBL_RANKING r 
 INNER JOIN TBL_USERS u 
    ON u.id = r.userid 
  LEFT JOIN (SELECT name FROM ".TBL_GAME." WHERE active = '1' ORDER BY rand() LIMIT 1)  temp1
    ON r.game=temp1.name
  LEFT JOIN (SELECT name FROM ".TBL_FORMAT." WHERE active = '1' ORDER BY rand() LIMIT 1)  temp2
    ON u.format=temp2.name
 WHERE r.type = '1' 
   AND temp1.name != ''
   AND temp2.name != ''
 ORDER BY r.points DESC LIMIT 5