Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MariaDB Dynamic Columns & JSON?

I am trying to store JSON data (pretty much an array in PHP that could be unknown length) in a column which would allow me to do where queries on it. Let's use this as an example...

Say I have a field asking what sort of sports you like (and it's a checkbox).

[] Soccer
[] Hockey
[] Football
[] Swimming

Which would then be sent via sports[] array to PHP. I then want to take this and add it to my database so it looks like

|sports|{hockey:false,swimming:true,football:false,soccer:true}|

Or something like that, which I could then maybe go

SELECT COUNT(*) FROM fields WHERE hockey = "false";

And I can't seem to figure out how to properly do this, ignore the fact that this "example" could actually easily be done by joining I want to do it using mariadb dynamic columns (at least I believe that's what I want). I know I can do this using Postgre.

like image 342
Steven Avatar asked Apr 15 '14 14:04

Steven


1 Answers

It's all here: https://mariadb.com/kb/en/dynamic-columns/

The dynamic columns are stored inside a real blob column and inserted like that:

insert into data
values (data_id, user_id, COLUMN_CREATE(<dcolumn1>, <value1>, <dcolumn2>, <value2>, ...));

So you would not use json here, instead serialize the data this way:

$dynamic = array()
foreach($_POST['sports'] as $sport) {
    $dynamicData[] = "'" . $sport . "'", TRUE;
}
$dynamicColumn = join(', ', $dynamicData);

Will generate something like

'hockey', TRUE, 'soccer', TRUE

To search all rows for ppl playing soccer:

... where COLUMN_GET(dynamic_blob, 'soccer' as soccer) = TRUE; 
like image 197
Daniel W. Avatar answered Sep 22 '22 14:09

Daniel W.