2011-10-11 64 views
-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 
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

嘗試有子查詢中使用左加入

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 
+0

固定!完美,你能解釋一下代碼,所以我理解主要變化,爲什麼? – sark9012

+0

我使用了LEFT JOIN,它反映了WHERE SubQueries語句中的條件,並使用temp1.name!=''AND temp2.​​name!=''的條件消除了所有的空值 – Bryan