I´m new to MySql and I´m having a problem ordering the result of a query.
I have 2 tables:
Table1 contains the users of my system
userId userName
01 Ken
02 John
03 Bob
04 Steve
Table2 contains the followers of each user
userId, FollowerId.
02 01
01 02
02 03
02 04
so, in this case John has 3 followers: Ken, Bob and Steve.
I would like to generate a third table with 2 columns: users of the database and Number of followers per User. I would like to have the table ordered by Number of followers.
userId NrFollowers
02 3
01 1
03 0
04 0
at the moment I´m using the following code
$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
This solutions is not optimised as required an loop for each databases`s user and does not allow to order the users by number of followers.
Can someone please help me to write the proper Mysql query?