[英]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. 我有3个表News,News_tag和Tag,News_tag与新闻和Tag之间的多对多关系。 I want make sql query to get all tags with corresponding news count. 我想让sql查询获取具有相应新闻计数的所有标签。 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. 不要忘记外部联接具有带有0条新闻的标签。
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 在此处查找语法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
: 假设在Tag
和News_tag
中都有一个名为tag
的列,并且您正在寻找每个Tag
的News
项目数:
SELECT Tag.tag, COUNT(*)
FROM Tag
INNER JOIN News_tag ON News_tag.tag = Tag.Tag
GROUP BY Tag.tag
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.