我是MySql的新手,我在订购查询结果时遇到问题。mysql查询多个表和计数行
我有2个表:
表1包含了我的系统的用户
userId userName
01 Ken
02 John
03 Bob
04 Steve
表2包含了每个用户的追随者
userId, FollowerId.
02 01
01 02
02 03
02 04
所以,在这种情况下,约翰有3个追随者:肯,鲍勃和史蒂夫。
我想生成包含2列的第三个表格:数据库的用户和每个用户的关注者数量。我希望按照关注者数量排列表格。使用以下代码
$stmt = $conn->prepare("SELECT userId, userName FROM Table1");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($userId, $userName);
while($stmt->fetch()) {
//count number followers
$stmtfl = $conn->prepare("SELECT * FROM Table2 WHERE userId = (?)");
$stmtfl->bind_param("s", $userId);
$stmtfl->execute();
$stmtfl->store_result();
$stmtfl->fetch();
$followCount= $stmtfl->num_rows;
//now I have $userName and $NrFollowers
此解决方案
userId NrFollowers
02 3
01 1
03 0
04 0
此刻I'm根据需要为每个用户databases`s一个循环,并且不允许通过的数目订购用户没有被优化追随者。
有人可以帮我写适当的Mysql查询吗?
非常感谢你。我看了一下演示。这正是我所期待的:) – zorzihit