MySQL COUNT with INNER JOIN

时间:2016-04-28 23:06:55

标签: mysql

The following query returns me the total of 2 rows instead of 1 because it happens the video to have two categories associated.

SELECT COUNT(video.id) AS `total`
FROM `videos` AS `video`
INNER JOIN `videos_categories` AS `video_category` ON `video_category`.`video_id` = `video`.`id`
INNER JOIN `categories` AS `category` ON `category`.`id` = `video_category`.`category_id`
WHERE video.title = 'John Mcane' OR category.description = 'Traditional'

The table videos_categorieshas two lines and that's the problem.

id | video_id | category_id
1    1          1
1    1          2

I can make a count to my array in PHP but that's not correct. Any ideas of how can I solve this? Group by didn't work.

1 个答案:

答案 0 :(得分:0)

COUNT(X)计算它遇到的X值的总数不为空,COUNT(DISTINCT X)应该给你你想要的东西(假设X是一个唯一的字段)。