开发者

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜