Home > Enterprise >  In SQL, how to select with alias as array?
In SQL, how to select with alias as array?

Time:09-24

I've been trying and Googling for quite some time now to find out how to get the following output as the result of a MySQL query:

Array
(
[id] => 85
[values] => Array(
                  [first_value] => 676
                  [second_value] => 383
                  [third_value] => 876
)          
)

One of my failed efforts as for the MySQL query:

select id, first_value as values[], second_value as values[], 
third_value as values[] from.....

What would be the right way to go? Many thanks for your support, Louis.

CodePudding user response:

There's no support for "arrays" in a result set. There are no arrays in MySQL.

You can produce a comma-separated string:

SELECT id, CONCAT_WS(',', first_value, second_value, third_value) AS `values`
...

But that's not an array. It's just a string that contains commas (or other symbol you choose). Then it's up to the caller to explode that string.

See CONCAT_WS() for documentation on that function.

  • Related