我有2个表用户|讯息。
posts
结构是:
[post_id
| post_user_id
]
users
结构是:
[user_id
| user_name
| user_password
]
现在我希望获得帖子的前5位用户
编辑1:
$cod_sql = "select u.user_name, count(*) as 'TotalNumberofPosts'
from users u
join posts p
on u.user_id=p.post_user_id
group by user_name
order by count(*) desc
limit 5";
$top10 = mysql_query($cod_sql1) or die (error_sql(mysql_error(),__LINE__,__FILE__));
echo '<div class="head_panel">Members</div>
<div class="body_panel">
<table border="1" width="100%">
<tr>
</tr>
<tr class="tr3">
Top5 :
</tr>';
if ( $top10 === FALSE )
{
// An error has occured
print "There was an error running the query" . mysql_error();
} else {
while ( $row = mysql_fetch_assoc($top10) )
{
print "This is some data from a row<BR />";
print "Name: ($row) <BR />";
}
}
}
break;
答案 0 :(得分:1)
我想这会做。我现在无法验证脚本,所以请告诉我它是否有效。
select *
from users
where exists (
select * from posts
where users.user_id=posts.post_user_id)
order by users.user_id
limit 5
答案 1 :(得分:1)
以下代码将计算每个用户的帖子总数,并仅显示前5个海报。 SQL Fiddle demonstration
select u.user_name, count(*) as 'TotalNumberofPosts'
from users u
join posts p
on u.user_id=p.post_user_id
group by user_name
order by count(*) desc
limit 5