2012-02-17 116 views
0

我需要查詢幫助。我有一個「成員」表和一個「評論」表。MySQL組合數據+計數(*)查詢來自2個表

members: userid,name,bday etc... 
comments: id,userid,message,rel etc... 

直到現在我使用了2個查詢membersdata和commentsCount,並在PHP中結合使用。

我的問題。只有一個查詢可以同時獲得兩個(全部來自成員& &評論數)嗎?

這不是workung ...

SELECT members.*, count(comments.*) as count 
FROM members, comments 
WHERE members.userid=comments.userid 
group by members.userid 

是否有人知道的其他解決方案?

+0

爲什麼不工作?語法錯誤?或者它返回什麼? – 2012-02-17 00:46:21

回答

2

這是你查詢的清理後的版本,假設你要爲每個useridnumber of comments

SELECT members.userid, count(*) as count 
FROM members 
INNER JOIN comments 
ON members.userid = comments.userid 
GROUP BY members.userid 

我解決的問題:

  1. 只選定列是無論是在group by子句,或者具有應用於它們的聚合函數。這是不正確的選擇不符合任何這些標準(雖然MySQL允許你這樣做)
  2. 代替隱有明確加入連接列,並搬離where子句on條款
  3. 代之以select ... count(comments.*)加盟條件select ... count(*)count(*)工程就好了
+0

Inner Join ftw。 – 2012-02-17 00:59:46

0

謝謝你馬特 我用你的版本。而im的學習是sql連接。

我的代碼的問題是'count(comments。*)'。 Mysql不喜歡這個!

這是工作:

SELECT members.*, count(comments.rel) as count 
FROM members, comments 
WHERE members.userid=comments.userid 
group by members.userid