我有一个多次包含相同用户ID的表。
我想返回9个用户名最多的用户的图片。
如何选择行数最多的用户和从最多到最少的用户?
这可能很容易,但我找不到答案。
$sql ="SELECT * FROM beoordelingen,users WHERE beoordelingen.userid=users.userid
GROUP BY beoordelingen.userid LIMIT 9 ";
$result = $conn->query($sql) or die ("The query could not be completed. try again");
$cols=3;
echo "<table width='150' border='0' cellpadding='0'>"; // The container table with $cols columns
do{
echo "<tr>";
for($i=1;$i<=$cols;$i++){ // All the rows will have $cols columns even if
// the records are less than $cols
$row=mysqli_fetch_array($result);
if($row){
echo"<td>
<table width='150' border='0' cellpadding='0'>
";
if ($row["userimage"] == '') {
echo "<a href='user.php? id=" . $row['userid'] . "'</a><img src='Images/users/nopicture.png' alt='nopicture'
class='userimage-tooltip-large' title='".$row['username']."''>";
} else {
echo "<a href='user.php? id=" . $row['userid'] . "'</a><img src='Images/users/".$row['userimage']."'
class='userimage-tooltip-large' title='".$row['username']."''>";
}
echo"</table>
</td>";
} else {
echo "<td> </td>"; //If there are no more records at the end, add a blank column
}
}
} while($row);
echo "</table>";
答案 0 :(得分:1)
使用userid添加行数,按降序排序,然后使用限制: -
SELECT users.userimage,
users.userid,
users.username,
COUNT(*) AS userid_count
FROM beoordelingen
INNER JOIN users
ON beoordelingen.userid=users.userid
GROUP BY beoordelingen.userid
ORDER BY userid_count DESC
LIMIT 9
请注意,未定义除userid之外的列的值。如果你想要特定行的值,那么这有点复杂,你需要定义哪一个。