[英]MySQL query from three different tables
I built working MySQL query: 我建立了工作的MySQL查询:
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
. 现在,我想添加第三个表,并从表
comments
中video_ID
count()
结果,其中该表中的video_ID
将与表video
中的video_ID
相等。
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. 作为回报,我想获得与某些
video_ID
相关的评论数。
I don't understand how to make it work correctly in one query. 我不明白如何在一个查询中使其正常工作。
Could you please help me out? 你能帮我吗?
Thank you in advance, 先感谢您,
Ilia 伊利亚
If you are using an aggregate function like a COUNT
in a query, you need to specify the grouping with a GROUP BY
clause. 如果在查询中使用诸如
COUNT
类的聚合函数,则需要使用GROUP BY
子句指定分组。
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. 虽然MySQL允许您省略
GROUP BY
子句的某些元素,但是最好指定它们。
When joining two tables, it is good practice to use the INNER JOIN
syntax, rather than a WHERE
filter. 连接两个表时,最好使用
INNER JOIN
语法,而不是WHERE
过滤器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.