2014-09-20 33 views
1

我正在嘗試爲我的管理面板開發一個功能,該功能根據它們可能具有的任何「標誌」獲取評論。我想要從評論表中獲取結果,但只能在標記表中關聯行的註釋。然後,我想根據評論的標誌總數來排列結果。爲什麼在使用group by和left join時出錯?

這是我的表結構:

CREATE TABLE IF NOT EXISTS `article_comments` (
    `comment_id` int(15) NOT NULL AUTO_INCREMENT, 
    `author_id` int(15) NOT NULL, 
    `article_id` int(15) NOT NULL, 
    `modifier_id` int(15) NOT NULL, 
    `content` varchar(255) NOT NULL, 
    `date_posted` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 
    `date_modified` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', 
    PRIMARY KEY (`comment_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ; 

CREATE TABLE IF NOT EXISTS `article_comment_flags` (
    `flag_id` int(15) NOT NULL AUTO_INCREMENT, 
    `comment_id` int(15) NOT NULL, 
    `member_id` int(15) NOT NULL, 
    `date_flagged` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, 
    PRIMARY KEY (`flag_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; 

這是我使用的當前查詢:

SELECT 
     c.comment_id AS comment_id, c.article_id, 
     f.flag_id, f.comment_id, f.member_id, f.date_flagged, COUNT(f.flag_id) AS total_flags 
    FROM article_comments AS c 
    LEFT JOIN article_comment_flags AS f ON (c.comment_id = f.comment_id) 
    GROUP BY comment_id 
    ORDER BY total_flags DESC 
    LIMIT 5 

這是我得到當前的SQL錯誤:

Column 'comment_id' in group statement is ambiguous 

任何人有任何想法?

+0

它的別名 - 通過c.comment_id'使用'組,而不是... – sgeddes 2014-09-20 01:48:17

回答

2

你必須指出它將被編組爲comment_id。所以,你必須改變路線:

GROUP BY comment_id 

GROUP BY c.comment_id 
+1

考慮OP是選擇'C .comment_id',我想這將是正確的分組。 – sgeddes 2014-09-20 01:49:36

0

欄目組聲明 'COMMENT_ID' 不明確:

SELECT 
c.comment_id AS comment_id, 
f.comment_id 
FROM article_comments AS c 
LEFT JOIN article_comment_flags AS f ON (c.comment_id = f.comment_id) 
GROUP BY comment_id 
  • 他們是平等的,所以你只需要一個從左邊拿一個,因爲它總是在那裏,所以從選擇部分刪除f.comment_id。
  • 你可以寫USING(comment_id)而不是ON(..),那麼你只能得到這個列一次。
  • 明確地告訴,至極列GROUP BY,從左側這裏最好使用c.comment_id