【问题标题】:How do I convert a column to an array in mysql?如何在mysql中将列转换为数组?
【发布时间】:2020-08-14 20:48:39
【问题描述】:

我有一个 2 列的表,user_id 和 connection_type。这两个字段都不是唯一的。一个用户 id 可以出现多次,一种连接类型可以出现多次。如何将所有连接类型分组到一个用户 ID?

Table I have:

schema: 
user_id -- INT 
connection_type -- STRING

user_id connection_type 
101     4g 
102     3g 
101     4g 
101     2g 
102     2g 
101     4g 
102     4g 
101     4g 
102     4g 
101     4g

Table I need from the above:

user_id connection_type 
101     ['4g','4g','2g','4g','4g','4g'] 
102     ['3g','2g','4g','4g']

【问题讨论】:

  • 向我们展示您的代码,以便我们提供帮助。
  • 考虑在应用程序代码中处理这个
  • 在数据中似乎没有任何东西可以保证数组中元素的特定顺序。从显示的数据来看,102 ['4g','2g','4g','3g'](不同顺序的元素)看起来同样有效。 (在有人说这不是对所提问题的回答之前,这就是为什么我将其发布为 comment 而不是 answer

标签: mysql sql arrays group-by


【解决方案1】:

MySQL 本身不支持数组 - 但如果您想要 JSON 数组,您可以这样做:

select user_id, json_arrayagg(connection_type) connection_types
from mytable
group by user_id

【讨论】:

    【解决方案2】:

    你可以在 MySQL 中使用group_concat 函数:

    查询如下:

    select user_id,
    group_concat(",",Connection_type) as connecttion_type
    from table
    group by user_id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-19
      • 2014-04-30
      • 2019-05-31
      • 2021-10-20
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多