2014-09-23 70 views
0

加入我有以下表格: MOVIESMySQL的正確與計數不正常

 +-------------+-------------+------+-----+---------+----------------+ 
     | 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; 

而這返回按喜好數排序的電影,但不是尚未投票(喜歡)的電影呢。出於某種原因,RIGHT加入只是簡單加入。 我已經搜索了一些相對的答案,但無法找到有用的東西。

回答

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

+0

謝謝John,這很有用! – gematzab 2014-09-25 09:29:44