计算列时出错,内部连接另一个表

时间:2014-03-16 05:34:07

标签: mysql count inner-join

我试图计算评论最多的新闻。我有两个表:评论和包含相同列的新闻:News_ID。这是查询

select *,count(News_ID) as count from comments inner join news where comments.News_ID = news.News_ID group by comments.News_ID order by count DESC limit 4

我收到此错误

#1052 - Column 'News_ID' in field list is ambiguous

这是否意味着我想要计算的专栏?

2 个答案:

答案 0 :(得分:1)

确保您在选择中news_idcomments.news_id

说明您获得的news.news_id内容
select 
    *,
    count(comments.News_ID) as count 
from comments 
inner join news where comments.News_ID = news.News_ID 
group by comments.News_ID 
order by count DESC limit 4

答案 1 :(得分:1)

您需要告诉您正在使用其列的表的名称,选择有两个News_ID列,因此在计数中它不明确,以便查询选择哪个表的列,也使用正确的语法进行连接with on clause

select n.*,c.*,count(n.News_ID) as count 
from comments c
inner join news n ON(c.News_ID = n.News_ID)
 group by c.News_ID 
order by count DESC limit 4