V
V
Vladimir Shishmintsev2014-12-30 09:56:38
MySQL
Vladimir Shishmintsev, 2014-12-30 09:56:38

How to get an array in one of the fields in Mysql?

Good afternoon.
Maybe of course I want a lot from MySQL, but I would like to get an array in one of the fields.
Now I get its authors by id of the book, separated by commas:

SELECT 
    GROUP_CONCAT(DISTINCT `a`.`title` ORDER BY `a`.`title` ASC SEPARATOR ", ") AS `title`, 
    `b`.* 
FROM `book` as `b` 
    LEFT OUTER JOIN `book_author` AS `ba` ON (`b`.`id` = `ba`.`book_id`)
    LEFT OUTER JOIN `author` AS `a` ON (`ba`.`author_id` = `a`.`id`)
WHERE `b`.`id` = 4
    GROUP BY `b`.`id`

`title` | `id` | `name`
--------------------
A1, A2 | 4 | Book1
And I would like an array:
`title` | `id` | `name`
---------------------------------------------------- ---------------
| 4 | Book1

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vitaly Arkhipov, 2014-12-30
@Pingvi

dev.mysql.com/doc/refman/5.0/en/data-type-overview.html
As you can see, there are no arrays here.
So either make your own implementation (serialize as @VitaZheltyakov suggested ) or as you already did - with database normalization.
However, I note that there are nosql databases that will support such functionality out of the box, for example mongodb. However, this is a different approach to the database architecture and working with it.
Choose :-)

V
Vitaly Zheltyakov, 2014-12-30
@VitaZheltyakov

Don't reinvent the wheel - serialize the array and write. Better yet, save the array to a file or memcache

A
Alexey Zakharov, 2014-12-30
@Zakhar0v

ex:
table `book`

| id | title|  name |
|  1 | A1   | book1 |

request:
SELECT CONCAT_WS('::', FORMAT(`id`,0),`title`,`name`) as `bookArray` FROM `book` 
WHERE`id` =1

get-
| bookArray    |
| 1::A1::book1 |

CONCAT_WS is a concatenation with a delimiter (eg "::");
CONCAT is just a union;
FORMAT( `id` , 0 ) - cast int field to string;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question