我需要帮助限制内部联接。
表格
用户:
文件:
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 :(得分: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
答案 1 :(得分: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);
}