2011-02-13 77 views
0

我需要幫助限制內部連接。幫助限制內部連接

表:


用戶:

  • UID
  • 活性

文件:

  • FID

UID = FID


SELECT uid 
FROM users AS u 
INNER JOIN files AS x ON u.uid = x.fid 
WHERE u.left = '0' 
AND u.active = '1' 
ORDER BY `u`.`uid` ASC 

結果:

uid 
3 
3 
3 
3 
7 
47 
47 
47 
47 
47 
47 
47 
47 
47 
47 

我需要限制INNER JOIN 5。所以「uid」不會出現超過5次。像這樣:

uid 
3 
3 
3 
3 
7 
47 
47 
47 
47 
47 

更新:

這裏是PHP代碼

$res = do_sqlquery("SELECT uid FROM users as u INNER JOIN files as x ON u.fid=x.fid WHERE u.left = '0' AND u.active='1'"); 
    if (mysql_num_rows($res) > 0) 
    { 
     while ($arr = mysql_fetch_assoc($res)) 
     { 
     $x=$arr["uid"]; 
     quickQuery("UPDATE users SET pots = pots+".$GLOBALS["bui"]."*".$cleaint."/900 WHERE id = '$x'"); 
     } 
    } 
+0

什麼數據庫s erver? – 2011-02-13 10:29:02

回答

1

在MySQL:

SELECT CONCAT(`uid`, ":", MAX(5, COUNT(`fid`))) `uid_count` 
FROM ... 
GROUP BY `uid` 

給你類似的結果:

uid_count 
3:4 
7:1 
47:5 

在PHP中,例如,您可以獲取拆分後:

while (FALSE !== ($row = mysql_fetch_assoc($query))) { 
    ($uid, $count) = split(':', $row['uid_count'], 2); 
} 
+0

@Pablo聖克魯斯MySQL客戶端 – user614963 2011-02-13 13:52:58

2

一個MySQL唯一的解決方案,而無需使用PHP

SELECT uid 
from (
    SELECT u.uid, @r:= if(@u=u.uid,@r+1,1) r, @u:=u.uid 
    FROM users AS u 
    CROSS JOIN (select @u:=null) g 
    INNER JOIN files AS x ON u.uid = x.fid 
    WHERE u.`left` = '0' 
    AND u.active = '1' 
    ORDER BY u.uid ASC 
) U 
WHERE U.r <= 5 
ORDER BY uid ASC 

或更一般地,只是沒有MySQL變量的SQL

SELECT u.uid 
from (
    SELECT u.uid, count(*) C 
    FROM users AS u 
    INNER JOIN files AS x ON u.uid = x.fid 
    WHERE u.`left` = '0' 
    AND u.active = '1' 
    GROUP BY u.uid 
) U inner join (
    select 1 n union all select 2 union all select 3 
    union all select 4 union all select 5) V ON U.C>=V.n 
ORDER BY U.uid ASC 
+0

謝謝你,但沒有工作。結果是不正確的。我編輯了我的文章並添加了php – user614963 2011-02-13 13:49:58