MySQL正确加入计数不正常

时间:2014-09-23 08:48:06

标签: mysql join count

我有以下表格: MOVIES

        +-------------+-------------+------+-----+---------+----------------+
        | Field       | Type        | Null | Key | Default | Extra          |
        +-------------+-------------+------+-----+---------+----------------+
        | id          | int(11)     | NO   | PRI | NULL    | auto_increment |
        | user_id     | int(11)     | YES  | MUL | NULL    |                |
        | title       | varchar(40) | NO   |     | NULL    |                |
        | description | text        | NO   |     | NULL    |                |
        | created_at  | datetime    | YES  |     | NULL    |                |
        | updated_at  | datetime    | YES  |     | NULL    |                |
        +-------------+-------------+------+-----+---------+----------------+

MOVIE_VOTES

        +------------+------------+------+-----+---------+----------------+
        | Field      | Type       | Null | Key | Default | Extra          |
        +------------+------------+------+-----+---------+----------------+
        | id         | int(11)    | NO   | PRI | NULL    | auto_increment |
        | user_id    | int(11)    | YES  | MUL | NULL    |                |
        | movie_id   | int(11)    | YES  | MUL | NULL    |                |
        | like       | tinyint(1) | YES  |     | NULL    |                |
        | created_at | datetime   | YES  |     | NULL    |                | 
        | updated_at | datetime   | YES  |     | NULL    |                |
        +------------+------------+------+-----+---------+----------------+

我想查询按照他们喜欢的数量排序的所有电影。我有这个问题:

        SELECT *, COUNT(*) AS count_likes 
        FROM movie_votes 
        RIGHT JOIN movies 
        ON movies.id=movie_votes.movie_id 
        WHERE movie_votes.like = 1 
        GROUP BY movie_id 
        ORDER BY count_likes;

这将按照喜欢的数量排序电影但不是尚未投票(喜欢)的电影。出于某种原因,右连接用作简单连接。 我搜索了一些相关的答案,但找不到任何有用的东西。

1 个答案:

答案 0 :(得分:1)

在执行外部连接时应指定列名,以便它只计算非空

SELECT  movies.id, 
        movies.user_id,
        movies.title,       
        movies.description, 
        movies.created_at,
        movies.updated_at,
        COUNT(movie_votes.movie_id) AS count_likes 
FROM    movies
        LEFT JOIN movie_votes  
            ON  movies.id = movie_votes.movie_id 
                AND movie_votes.like = 1
GROUP   BY movies.id, 
        movies.user_id,
        movies.title,       
        movies.description, 
        movies.created_at,
        movies.updated_at
ORDER   BY count_likes

条件movie_votes.like = 1应放在ON子句中,以便在将其加入表movie_votes之前先过滤表movies中的行。