开发者

mysql select UNION with AND problem

in database, the table friendship has id, username and friendusername. When a user accept other user as friend, 1 row of record will be saved in the table (not 2 rows). I want to random select 15 users and display their pictures, mysql code :

<?php
$query120 = "SELECT frenusername FROM friendship WHERE username='{$username2}' UNION SELECT username FROM friendship WHERE friendusername='{$username2}' AND RAND()<(SELECT ((15/COUNT(*))*10) FROM friendship) ORDER BY RAND() LIMIT 15";
$result120 = mysql_query($query120,$connection) or die (mysql_error());
confirm_query($result120); 
while($userinfo120 = mysql_fetch_array($result120)){
    $frenusername= $userinfo120['frenusername'];
    $username = $userinfo120['username']; //this hold empty value, why?

    $query121 = "SELECT picturemedi开发者_JAVA技巧um FROM users WHERE username='{$frenusername} OR username='{$username}' LIMIT 1";
    //display picture
    }
}
?>

My problem 1 : Why $username hold empty value?

My problem 2 : The statement AND RAND()<(SELECT ((15/COUNT(*))*10) FROM friendship) ORDER BY RAND() LIMIT 15" is to random select 15 records from the table. Supposedly I need to write it on both UNION statements right? (meaning I need to write it for 2 times). If so, it will show 30 records instead of 15 records. Should I change it become 8/Count LIMIT 8 for each? Or is there any other way avoid duplicate the AND statement?


If you just need a random set of 15 friends of a username2, then you don't need the UNION:

(SELECT username 
FROM friendship 
WHERE (friendusername='{$username2}' OR 
username='{$username2}') AND 
RAND()<(SELECT ((15/COUNT(*))*10) FROM friendship) 
ORDER BY RAND() 
LIMIT 15)

The UNION will select everything from either SELECT. In your SQL, the first SELECT would get ALL of the usernames in the friendship table, then the second SELECT would get the random 15, but the UNION would select from either of the two SELECTs a record if it was in either of the two SELECT results. That's probably why you're seeing the extra users.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜