1

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?

3 Answers 3

1

For sql query, you can try this:

select
    tbl1.userId,
    count(distinct tbl2.FollowerId) as NrFollowers
from tbl1
left join tbl2
on tbl1.userId = tbl2.userId
group by tbl1.userId
order by count(distinct tbl2.FollowerId) desc

See demo here.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. I had a look on the demo. It is exactly what I was looking for :)
1
SELECT u.usersId, COUNT(f.FollowerId) AS NrFollowers
FROM users u
LEFT JOIN followers f ON f.userId = u.userId
GROUP BY u.userId

1 Comment

Thank you very much
1

use below code..

SELECT u.usersId, coalesce(COUNT(f.FollowerId) ,0)AS NrFollowers
FROM users u
LEFT JOIN followers f ON f.userId = u.userId
GROUP BY u.userId
order by coalesce(COUNT(f.FollowerId) ,0) desc

1 Comment

Thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.