简体   繁体   中英

Join of many to many tables

I have 3 tables News, News_tag and Tag, News_tag many to many relationship between news and Tag. I want make sql query to get all tags with corresponding news count. Please help.

SELECT COUNT(*) as news_count, t.*
FROM Tag t
    LEFT OUTER JOIN News_Tag nt
        ON t.id = nt.tag_id
GROUP BY t.id

Don't forget the outer join to have the tag with 0 news.

I need to know the coloumns to tell you the exact syntax however it will look something like;

SELECT TagName, COUNT(*)
FROM Tag t
INNER JOIN NEws_tag tn
   ON t.TagID = tn.TagID
INNER JOIN News n
   ON n.NewsID = tn.NewsID
GROUP BY TagName

Look here for deatails of the syntax http://dev.mysql.com/doc/refman/5.0/en/join.html

Without knowing the structures of the tables, it's difficult to give an answer. You probably want something like this

select news.subject, tag.subject
from news, news_tag, tag
where news.id = news_tag.news
and news_tag.tag = tag.id
order by tag.subject

Try and improve your acceptance rate.

SELECT COUNT(*)  
FROM news AS n 
LEFT JOIN (news_tag AS nt, tag AS t) 
ON ( 
    nt.tag_id = t.tag_id 
    AND 
    nt.news_id = n.id
)
WHERE (
    t.tag
    IN (
        '$tag'
    )
)

Assuming there's a column named tag in both Tag and News_tag , and that you're looking for the number of News items for each Tag :

SELECT Tag.tag, COUNT(*)
FROM Tag
INNER JOIN News_tag ON News_tag.tag = Tag.Tag
GROUP BY Tag.tag

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