2011-04-25 64 views
1

我有一個用戶表和意見表,我想從用戶的選擇,通過評論數量都從意見表,並責令其意見大金額的頂級用戶頂級用戶 - >評論 - > PHP

表結構

用戶

id | username | password 

評論

id | text | author_username 
+4

評論表應該由'author_userid'加入,而不是'author_username'可憐的表單。 – Dutchie432 2011-04-25 20:18:30

+0

還要確保你的'id'列是主鍵,以便索引它們以便更快地查詢。 – Treffynnon 2011-04-25 20:25:06

回答

0

我的SQL是有些生疏,但這樣的事情應該給你你在找什麼(但我說過,用戶ID應該是在comments表的唯一用戶標識符)。

Select count(id), author_username from comments group by author_username 
+0

以及如何在php中顯示計數? – Allan 2011-04-25 20:25:42

+0

我通常使用ODBC,所以我也不熟悉'mysql'語法。如果您不知道如何從數據庫中讀取字段,那應該是您的第一個問題,而不是如何形成數據。 – Dutchie432 2011-04-25 20:43:14

0
select u.username,count(c.comments) as total 
    from users as u 
    left join comments as c 
    on u.username = c.author_username 
    group by u.username 
    order by total desc 

我會改變連接字段爲dutchie432建議。添加一個限制條款,以獲得您想要的記錄數量。

3

使用以下MySQL語句列出評論最多的用戶。 CommentCount告訴你一個特定用戶發表的評論數量。

SELECT 
    users.username, 
    COUNT(comments.id) AS CommentCount 
FROM 
    users 
    INNER JOIN comments ON users.id = comments.author_userid 
GROUP BY 
    users.username 
ORDER BY 
    COUNT(comments.id) DESC 

請注意,您將不得不改變author_useridauthor_username第一!

+0

mysql上不存在top子句。 – 2011-04-25 20:25:22

+0

你死定了!我現在糾正了它。如果您只想瞭解前10名用戶,只需在您的MySQL語句中添加「LIMIT 10」即可。 – Fabianius 2011-04-25 20:37:44

+0

你就是現在! ;) – 2011-04-25 20:41:09