【问题标题】:How to select multiple values against single record in a column in postgresql [duplicate]如何在postgresql的列中针对单个记录选择多个值[重复]
【发布时间】:2023-04-10 07:51:01
【问题描述】:

我有两个具有多对多关系的表。

表 1:

    Code    |  Product | 
------------+----------+
 00001      | product1 | 
 00002      | product2 | 

表 2:

Tag_id |  name | 
-------+--------
1      | tag1  | 
2      | tag2  | 

关联表:

Tag_id  | Product_id 
--------+----------+
 1      | product1 | 
 1      | product2 | 
 1      | product3 | 
 2      | product4 |
 3      | product4 | 
 4      | product4 |

请告诉我如何生成表格 如下图所示:

  Code      |  Product | Tags 
------------+----------+---------------
 00001      | product1 | tag1,tag2
 00002      | product2 | tag1,tag3,tag4

或多列中的标签。

【问题讨论】:

  • 最好在结果表中分别获取每个标签 ID 的记录。
  • 我也想要,请问我该怎么做?
  • 您真正使用的是哪些 dbms?不要标记不涉及的产品...
  • Postgresql....!
  • 所以删除其他 dbms 标签。请原谅那些回答您问题的可怜人,而不是其他 dbms 产品。

标签: sql postgresql string-aggregation


【解决方案1】:

对于 mysql
试试这个

select Code,Product,Group_concat(name) from table1 
left join associatedTable on table1.product=associatedTable.product_id 
left join table2 on table2.tag_id=associatedTable.tag_id

【讨论】:

  • 这是用于哪个 dbms?
  • PostgreSQL 没有group_concat 函数,OP 已经在 cmets 中指出他们正在使用 PostgreSQL。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-23
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 2014-03-09
  • 1970-01-01
相关资源
最近更新 更多