2011-12-02 55 views
1

我試圖選擇有關其相應投票的評論和摘要統計。並非所有評論都有投票,而那些評論可以有超過1票。這是我的查詢:簡單的MySQL連接不起作用

select 
    `article-comments`.id, 
    `article-comments`.user as user_id, 
    concat(users.first_name, ' ', users.last_name) as name, 
    users.job_title, 
    users.company_name, 
    avatar, 
    `article-comments`.content, 
    datediff(now(), `article-comments`.date_added) as diff, 
    `article-comments`.date_added as date, 
    count(`comment-votes`.id) as votes_count, 
    sum(`comment-votes`.score) as votes_score 
from 
    `article-comments` left outer join `comment-votes` on `article-comments`.id = `comment-votes`.comment, 
    users 
where 
    `article-comments`.status = 1 
&& `article-comments`.article = $resource_id 
&& `article-comments`.user = users.id 
&& `comment-votes`.status = 1 
order by 
    `article-comments`.id asc 

它沒有連接,但只返回1行與它完美的作品。

任何想法?

+1

當你說它完美的作品,它給你你想要的結果,而在加入? –

+0

如果您簡化了查詢以隔離問題,那麼它會更容易幫助 - 在SELECT中取出不必要的列,並在WHERE子句中硬編碼值 - 什麼是$ table和$ resource_id? – mikel

+0

@Adam - 是的,減去2個總結統計count()和sum() – bcherny

回答

0

嘗試:

select 
       `article-comments`.id, 
       `article-comments`.user as user_id, 
       concat(users.first_name, ' ', users.last_name) as name, 
       users.job_title, 
       users.company_name, 
       avatar, 
       `article-comments`.content, 
       datediff(now(), `article-comments`.date_added) as diff, 
       `article-comments`.date_added as date, 
       count(`comment-votes`.id) as votes_count, 
       sum(`comment-votes`.score) as votes_score 
      from 
       `article-comments` left join `comment-votes` on (`article-comments`.id = `comment-votes`.comment), 
       users 
      where 
       `article-comments`.status = 1 
      && `article-comments`.$table = $resource_id 
      && `article-comments`.user = users.id 
      order by 
       `article-comments`.id asc 
+0

謝謝,但它仍然返回同一行:[ – bcherny

+0

使用聚合函數(如COUNT和SUM)將導致您看到的內容,單行總是。想想經典的「SELECT COUNT(*)FROM atable」來獲取該表中的行數。您應該使用GROUP BY和這些函數來獲取您需要的數據。 MySQL的默認行爲允許某人引用未包含在GROUP BY語句中的字段,這會導致一些不確定的結果。如果您想了解有關http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html#sqlmode_only_full_group_by主題的更多信息,請閱讀本文。 – wisefish