我有一个包含两个表,Users和Posts的数据库。我想编写一个php脚本,按顺序列出前20个用户名,其中包含他们发布的帖子数量。用户名字段是Users表中的cUsername。 Users表的intUserID字段和Posts表的intPosterID字段对应于彼此。
非常感谢任何帮助。谢谢!
答案 0 :(得分:2)
使用GROUP BY并计数。这将为您提供其计数的用户ID列表:
SELECT intPosterId, COUNT(*)
FROM Posts
GROUP BY intPosterId
ORDER BY COUNT(*) DESC
LIMIT 20
您可以在子查询中使用结果:
SELECT u.cUsername, pcnt.postCount
FROM Users AS u
INNER JOIN (
SELECT intPosterId, COUNT(*) as postCount
FROM Posts
GROUP BY intPosterId
ORDER BY COUNT(*) DESC
LIMIT 20
) AS pcnt
ON u.intUserId = pcnt.intPosterId
在PHP脚本中使用它:
<?php
$sql = '
SELECT u.cUsername, pcnt.postCount
FROM Users AS u
INNER JOIN (
SELECT intPosterId, COUNT(*) as postCount
FROM Posts
GROUP BY intPosterId
ORDER BY COUNT(*) DESC
LIMIT 20
) AS pcnt
ON u.intUserId = pcnt.intPosterId
';
$pdo = new PDO(
'mysql:host=your_host;dbname=your_db',
'username',
'password',
array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION)
);
$stmt = $pdo->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "{$row['cUsername']}: {$row['postCount']} <br />\n";
}