我有一个类似这样的数据库:
user_id photo_id
1 1
1 2
1 3
1 4
2 5
2 6
我想从中获取最受欢迎用户的列表。像这样:
Popular Users: 1 (4) & 2 (2)
我将如何在PHP中使用mysql进行此操作?
谢谢,库尔顿
PS:我对mysql命令了解很多,所以你不必愚弄它。谢谢!
答案 0 :(得分:14)
基本查询将是:
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);
答案 1 :(得分:5)
select user_id, count(user_id) as count from table order by count desc group by user_id
无论如何......
答案 2 :(得分:2)
这可以仅使用SQL命令来完成。这就是我要做的事情:
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名结果。
答案 3 :(得分:1)
数据库查询看起来像这样:
select user_id, count(photo_id) as c
from table group by user_id
order by c desc limit 5;
在PHP中,它看起来像这样:
$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'];
}
答案 4 :(得分:0)
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