简体   繁体   中英

MySQL query from three different tables

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM