我正在建立一个推荐系统,我只想显示推荐中的前1名,而不是全部。 这是代码
$movies = mysqli_query($db, "select * from practice");
while ($movie=mysqli_fetch_array($movies))
{
$users=mysqli_query($db,"select username from users where id =$movie[user_id]");
$username=mysqli_fetch_array($users);
$matrix[$username['username']] [$movie['image']] = $movie ['ratings'];
}
$users=mysqli_query($db,"select username from users where id=$_GET[id]");
$username=mysqli_fetch_array($users);
?>
<div class="panel panel-default">
<div class="panel-heading">
<h2>
<a class="btn btn-info" href="index.php"> Back </a>
</h2>
</div>
<div class="panel-body">
<table class="table table-striped">
<th>Clothes</th>
<th>Rating</th>
<?php
$recommendation=array();
$recommendation = getRecommendation($matrix,$username['username']);
foreach($recommendation as $movie => $rating) {
?>
<tr>
<td>
<?php echo "<img src='images/".$movie."' >"; ?>
</td>
<td>
<?php echo $rating ; ?>
</td>
</tr>
<?php } ?>
</table>
</div>
答案 0 :(得分:0)
您应该在SQL查询中使用LIMIT
。
LIMIT查询
如果从结果集中只需要指定数量的行,请在> query中使用LIMIT子句,而不是获取整个结果集并丢弃多余的数据。
MySQL有时会优化具有LIMIT row_count子句而没有HAVING子句的查询
mysql> SELECT * FROM ratings ORDER BY category;
+----+----------+--------+
| id | category | rating |
+----+----------+--------+
| 1 | 1 | 4.5 |
| 5 | 1 | 3.2 |
| 3 | 2 | 3.7 |
| 4 | 2 | 3.5 |
| 6 | 2 | 3.5 |
| 2 | 3 | 5.0 |
| 7 | 3 | 2.7 |
+----+----------+--------+
mysql> SELECT * FROM ratings ORDER BY category LIMIT 1;
+----+----------+--------+
| id | category | rating |
+----+----------+--------+
| 1 | 1 | 4.5 |
+----+----------+--------+