Reputation: 13412
I built working MySQL query:
SELECT
v.*, u.username
FROM
video AS v, users AS u
WHERE
v.type = 'public'
AND
v.user_ID = u.user_ID
Now I want to add a third table and count()
results from the table comments
where video_ID
from this table will be equal to those from the table video
.
I tried this but it wasn't successful:
SELECT
v.*, u.username, count(c.video_ID)
FROM
video AS v, users AS u, comments AS c
WHERE
v.type = 'public'
AND
v.user_ID = u.user_ID
AND
v.video_ID = c.video_ID
In return I want to get the number of comments related to certain video_ID
's.
I don't understand how to make it work correctly in one query.
Could you please help me out?
Thank you in advance,
Ilia
Upvotes: 0
Views: 77
Reputation: 51494
If you are using an aggregate function like a COUNT
in a query, you need to specify the grouping with a GROUP BY
clause.
Try this
SELECT
v.*,
u.username,
count(c.video_ID) AS comment_count
FROM
video AS v
INNER JOIN users AS u ON v.user_ID = u.user_ID
INNER JOIN comments AS c ON v.video_ID = c.video_ID
WHERE
v.type = 'public'
GROUP BY
v.id,
u.username,
v.v.add_time
ORDER BY
v.add_time
While MySQL lets you leave out the some elements of the GROUP BY
clause, it is good practice to specify them.
When joining two tables, it is good practice to use the INNER JOIN
syntax, rather than a WHERE
filter.
Upvotes: 7