I need help limiting inner join.
Tables:
users:
- uid
- left
- active
files:
- 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
result:
uid
3
3
3
3
7
47
47
47
47
47
47
47
47
47
47
I need to limit INNER JOIN to 5 . so "uid" will not show up more than 5 times. like:
uid
3
3
3
3
7
47
47
47
47
47
update:
Here is the php code
$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"]."*"开发者_如何学JAVA.$cleaint."/900 WHERE id = '$x'");
}
}
A MySQL only solution, without using 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
or more generally, just SQL without MySQL variables
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
In MySQL:
SELECT CONCAT(`uid`, ":", MAX(5, COUNT(`fid`))) `uid_count`
FROM ...
GROUP BY `uid`
Gives you results like:
uid_count
3:4
7:1
47:5
In PHP, for example, you can then split after fetching:
while (FALSE !== ($row = mysql_fetch_assoc($query))) {
($uid, $count) = split(':', $row['uid_count'], 2);
}
精彩评论