我有一个类似于以下结构的数据库:
user_id photo_id
1 1
1 2
1 3
1 4
2 5
2 6
我想从it中获取最受欢迎的用户列表。就像这样:
Popular Users: 1 (4) & 2 (2)
我该如何在PHP中使用mysql来执行这个操作?
谢谢,Coulton
附注:我对mysql命令有一定的了解,所以不必过于简化。谢谢!
我有一个类似于以下结构的数据库:
user_id photo_id
1 1
1 2
1 3
1 4
2 5
2 6
Popular Users: 1 (4) & 2 (2)
基本查询应该是:
select user_id, count(user_id) as cnt
from yourtable
group by user_id
order by cnt desc
为了显示结果,类似如下代码:$results = array()
while($row = mysql_fetch_assoc($query_result)) {
$results[] = "{$row['user_id']} ({$row['cnt']})"
// repeat for however many results you want
}
echo "Popular user: ", implode(" & ", $results);
select user_id, count(user_id) as count from table order by count desc group by user_id
无论如何,类似于这样的东西...
SELECT user_id, count(user_id) uid_count
FROM <<table>>
GROUP BY user_id
ORDER BY uid_count DESC
LIMIT 5;
GROUP BY 收集所有具有相同 user_id 的行,ORDER BY... DESC 按降序对结果进行排序,因此前面的行代表最受欢迎的用户。LIMIT 给出前 5 个结果。
数据库查询将类似于以下内容:
select user_id, count(photo_id) as c
from table group by user_id
order by c desc limit 5;
$sql = 'select user_id, count(photo_id) as c from table group by user_id order by c desc limit 5';
$result = mysql_query($sql, $link);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['user_id'];
echo $row['c'];
}
SELECT COUNT(a.category_id) as cnt,b.category,b.image FROM bookings as a
INNER JOIN service_category as b ON a.category_id=b.category_id
GROUP BY a.category_id ORDER BY cnt DESC LIMIT 6