MYSQL防止特定表字段中的重复

时间:2014-03-23 16:23:45

标签: mysql duplicates

我是mysqli的新手,正在查询一个名为电影和电影评论的表格。我正在尝试获取电影的订阅源,这些电影按哪部电影的最新评论排序。这是我目前使用的代码:

select movies.id, movies.movie_title, movies.movie_description, movies.movie_url, movies.movie_actors, movies.movie_thumbnail, movies.time_uploaded, movies.movie_categories from movie_comments left join movies on movie_comments.movies_id = movies.id where movie_status=1 ORDER BY movie_comments.time_posted DESC LIMIT 10;

我遇到的问题是,如果评论有两条评论,它会两次获得同一部电影,因为它有两个注册评论计数,如下图所示:

enter image description here

如您所见,第一列id具有重复项(在本例中为id 129)。知道如何修改查询以防止重复的结果出现在ID字段中吗? db中包含这些重复项的表位于movie_comments中,该字段称为movies_id。

1 个答案:

答案 0 :(得分:0)

您为每条评论添加了一行,因为这是您选择的表格,相反,您可以汇总结果,例如:

SELECT      m.id, 
            m.movie_title, 
            m.movie_description, 
            m.movie_url, 
            m.movie_actors, 
            m.movie_thumbnail, 
            m.time_uploaded, 
            m.movie_categories 

FROM        movie_comments mc

LEFT JOIN   movies m
    ON      mc.movies_id = movies.id 

WHERE       movie_status=1 

GROUP BY    m.id, 
            m.movie_title, 
            m.movie_description, 
            m.movie_url, 
            m.movie_actors, 
            m.movie_thumbnail, 
            m.time_uploaded, 
            m.movie_categories

ORDER BY    MAX(mc.time_posted) DESC 

LIMIT 10;