PHP MySQL select random rows

前端 未结 6 1469
深忆病人
深忆病人 2021-02-15 16:47

I have a problem selecting 6 random friends

This is the query I\'ve got so far:

$result = num_rows(\"SELECT * FROM friends WHERE member_id = \'\".$_S         


        
相关标签:
6条回答
  • 2021-02-15 17:23

    If you use:

      SELECT * 
        FROM friends 
       WHERE member_id = '".$_SESSION['userid']."' 
    ORDER BY rand() 
       LIMIT 6
    

    If the person only has 3 friends, the query will only show those three - it doesn't mean that the query will always return six rows.

    0 讨论(0)
  • 2021-02-15 17:26

    Never mind, I figured it out :)
    Had to use while not for :'D

    0 讨论(0)
  • 2021-02-15 17:33

    The best way I've found to select any number of random records is with OFFSET in the query.

    Let's say you want 6 random records, so I'll borrow from an answer above and count the total number of friends in the database.

    $sql = mysql_query("SELECT COUNT(*) AS total FROM friends WHERE member_id='". $_SESSION['userid'] ."'");
    
    $get_count = mysql_fetch_array($sql); // Fetch the results
    
    $numfriends = $get_count['total']; // We've gotten the total number
    

    Now we'll get the 6 random records out of the total above (hopefully it's > 6),

    $query = mysql_query("SELECT * FROM friends WHERE member_id='". $_SESSION['userid'] ."' LIMIT 6 OFFSET " . (rand(0, $numFriends));
    
    
    while ($rows = mysql_fetch_array($query))
    {
      /// show your $rows here
    }
    

    Using OFFSET may not be the best or most efficient, but it's worked for me on large databases without bogging them down.

    0 讨论(0)
  • 2021-02-15 17:39

    change limit 1 to limit 6 on the eighth line.

    0 讨论(0)
  • 2021-02-15 17:40

    First select the number of friends that the user has:

    "SELECT COUNT(*) as numFriends FROM friends WHERE member_id='".$_SESSION['userid']."'
    

    ...put that into a variable, let's call it "$numFriends" Then:

    for($z=0;$z<6;$z++)
    {
       $randomFriendIndex = rand(1,$numFriends);
       //Get the friend at that index
    }
    
    0 讨论(0)
  • 2021-02-15 17:45

    Instead of SELECT * at the beginning, try SELECT COUNT(*) and use the actual return value instead of num_rows().

    Your loop could generate duplicates. I would suggest trying OMG Ponies answer.

    There is a whole chapter about random selection in the book SQL Antipatterns.

    0 讨论(0)
提交回复
热议问题