简体   繁体   English

当另一行具有相同的 id 但列中的值不同时,如何在 SQL 中选择一行?

[英]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?现在我的问题是:我怎样才能在这篇文章上只获得一篇文章但有多个标签?

screenshot of query in database数据库查询截图

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.

相关问题 我如何从一个表中选择同一行为另一张表中的不同值+ SQL - how do i select the same row from one table for different values in another table + sql 如何将一列的值复制到同一行的另一列? - How do I copy the value of one column into another in the same row? 在多行中查找同一列中具有相同值的行,而另一列具有不同值 - Find row that has same value in one column over multiple rows while another column has different values 从表中选择行,其中具有相同id的另一个表中的行在另一列中具有特定值 - Select rows from a table where row in another table with same id has a particular value in another column Select 一行具有相同的 id 并且匹配另一个表中另一列中的值 - Select one row with same id and match value in another column from another table 我如何 select 多行,其中一行在列中具有特定值? - How do I select multiple rows where one row has a specific value in a column? 在MySQL中,如何在更新同一行中的另一列时自动为该列设置值? - In MySQL, how do you automatically set a value for one column when updating another in the same row? 选择一行,而不是多个具有相同ID和不同值的行 - Select one row instead multiple with same id and different value 选择具有ID的行,其他列中的值不同SQL Access - Select row with ID, different value in other column SQL Access 如何从上一行的相同列值中选择列值最近减少的行? - How do I select row with the most recent reduction in a column value from same columns value in previous row?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM