PHP While 循环未运行 MySQL 数据库中所有选定的记录
我的博客下面有三张表:一张用于用户,一张用于评论,一张用于主题。 并非所有检索到的记录都会由 PHP 回显,我认为这可能与 NULL 值有关,例如在我的会员列表页面上,以下查询检索四个用户的数据:
SELECT COUNT(Topics.MemberID) AS NumberOfTopics, Users.id,
Users.FirstName, Users.LastName, Users.Joined
FROM Users LEFT JOIN Topics ON Users.id=Topics.MemberID GROUP BY Topics.MemberID
但是,如果列表末尾的最后一个用户没有主题 (NumberOfTopics = 0) 它们不会被呈现。 如果用户的帖子计数为 0,但他们关注的记录的帖子计数不为 0,则会显示该用户。为什么?
这是完整的代码:
$result = mysql_query("SELECT COUNT(Topics.MemberID) AS NumberOfTopics, ".
"Users.id, Users.FirstName, Users.LastName, Users.Joined ".
"FROM Users LEFT JOIN Topics ON Users.id=Topics.MemberID ".
"GROUP BY Topics.MemberID")
or die("Query failed with error: ".mysql_error());
echo "<table border='1'>
<tr>
<th>Name</th>
<th>Joined</th>
<th>No. of posts</th>
</tr>";
while($row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td><a href='/neuro/profile.php?userid=$row[id]'>" .
$row['FirstName'] . " " . $row['LastName'] . "</a></td>";
echo "<td>" . $row['Joined'] . "</td>";
echo "<td>" . $row['NumberOfTopics'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
感谢您的阅读!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我相信问题在于您的 GROUP BY 将强制消除 NULL 。
我通常会在这些情况下使用子查询,因为它更容易阅读和理解:
I believe the problem is that your
GROUP BY
will force the elimination ofNULL
s.I normally will use subquery in these circumstances simply because it is easier to read and understand:
我想这是因为你的group by。
尝试:
这应该收集您在子查询中查找的主题计数,然后将这些计数与所有用户进行左连接。
I think it's because of your group by.
Try:
This should gather the count of topics that you're after in a sub query and then left join those counts against all users.
你的询问有些矛盾。
LEFT JOIN
将返回左表中的所有行,即使右表中没有匹配项。然而,在您的查询中,您将按 Topics.MemberID 对记录进行分组。对于没有发帖的用户,他们将不会显示任何记录!尝试以下查询:Your query is somewhat contradictory.
LEFT JOIN
will return all rows from the left table, even if there are no matches in the right table. HOWEVER in the case of your query you are grouping your records by Topics.MemberID. For users with no post their will be no record shown!! Try the following query:您的查询似乎不正确。
我会使用内部联接
Your query seems incorrect.
I'd use an inner join