[英]How do I select one row in SQL when another row has same id but a different value in a column?
I am creating a website where you can share posts with multiple tags, now I encountered the problem that a post is shown multiple times, each one with one tag.我正在创建一个网站,您可以在其中共享具有多个标签的帖子,现在我遇到了一个帖子被多次显示的问题,每个帖子都有一个标签。 In my database I have a table posts and a table tags where you link the post_id.在我的数据库中,我有一个表帖子和一个表标签,您可以在其中链接 post_id。 Now my question is: how can I get only one post but multiple tags on this one post?现在我的问题是:我怎样才能在这篇文章上只获得一篇文章但有多个标签?
This should work, edit column names if needed:这应该可以工作,如果需要,编辑列名:
SELECT *,
(SELECT GROUP_CONCAT(DISTINCT tag) FROM tags WHERE post_id = posts.id)
FROM posts
You can use GROUP_CONCAT() in MySQL and string_agg() in MS SQL Server您可以在 MySQL 中使用 GROUP_CONCAT(),在 MS SQL Server 中使用 string_agg()
SELECT posts.id,GROUP_CONCAT(tags.tag)
FROM posts
Left JOIN tags on tags.post_id = posts.id
GROUP BY posts.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.