简体   繁体   中英

Select from 3 tables with one-to-many relation

I have a question.In my database I have 3 tables:

Articles:

id  title  content  date

Tags:

id  name

Tags_in_news:

id  news_id  tag_id

Where news_id is foreign key for news table and tag_id is foreign key for tag table...How to select the articles and all tags attached to them? I create a query but it select a news for each tag:

SELECT * FROM articles join tags_in_news
ON articles.id = tags_in_news.news_id
join tags on tags.id = tags_in_news.tag_id
ORDER BY date DESC

Try GROUP BY article and grouping tags as comma separated value
something like this:

SELECT 
date, a.title, GROUP_CONCAT(DISTINCT t.name) as tags_attached
FROM articles a 
JOIN tags_in_news tin ON a.id = tin.news_id
JOIN tags t ON t.id = tin.tag_id
GROUP BY a.id
ORDER BY date DESC

Your query is pretty close, and since you are doing joining it will list all the matching rows and you will get multiple rows for article per tag. In mysql there is a function called group_concat() which you can use along with group by so that all the tags associated with an article is concat by a comma and then display it for each article.

select
a.title,
a.content,
a.date,
group_concat(t.name) as name
from tags_in_news tin
inner join article a on a.id = tin.news_id
inner join tags t on t.id = tin.tag_id
group by a.id

DEMO

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