简体   繁体   English

在 Mysql 中,我们可以从子查询中返回一个数组吗

[英]In Mysql, can we return an array from a subquery

In postgres, if we want to retrieve any array of data from a subquery we just use array constructor.在 postgres 中,如果我们想从子查询中检索任何数据数组,我们只需使用数组构造函数。 Similarly to that in Mysql, is there any way to retrieve an array of data from a subquery?与Mysql类似,有没有办法从子查询中检索数据数组?

Example:例子:

  • In role we have schema like id, name, description在角色中,我们有像 id、name、description 这样的模式
  • In user table we have like id, email在用户表中,我们有像 id,email
  • In user_role table we have schema like id, role_id,user_id在 user_role 表中,我们有像 id、role_id、user_id 这样的模式

user_role hasMany roles. user_role 有很多角色。

I need a result like user_role.id,role.name and role.name should have an array of values.我需要像 user_role.id、role.name 和 role.name 这样的结果应该有一个值数组。

Please check below example https://mkyong.com/database/convert-subquery-result-to-array/请检查以下示例https://mkyong.com/database/convert-subquery-result-to-array/

mysql doesn't have an array type. mysql 没有数组类型。 You can return a comma separated list of role names:您可以返回以逗号分隔的角色名称列表:

select user.id, group_concat(role.name order by role.name)
from user
join user_role on user_role.user_id=user.id
join role on role.id=user_role.role_id
group by user.id

or a string containing a json array, eg ["role a name","role b name"] :或包含 json 数组的字符串,例如["role a name","role b name"]

select user.id, json_arrayagg(role.name order by role.name)
from user ...

Note that group_concat returns a string that will be truncated at @@group_concat_max_len characters, a system variable that defaults to 1024 in mysql.注意group_concat返回的字符串会在@@group_concat_max_len个字符处被截断,这是一个系统变量,在mysql中默认为1024。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM