2017-02-25 93 views
1

我是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查詢嗎?

回答

1

對於SQL查詢,你可以試試這個:

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 

demo這裏。

+0

非常感謝你。我看了一下演示。這正是我所期待的:) – zorzihit

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 
+0

非常感謝你 – zorzihit

1

使用下面的代碼..

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 
+0

非常感謝你 – zorzihit