Consulta MySQL para devolver una estructura personalizada con valores como tipo de campo y títulos

Sorry for the bizarre title, isn't easy to summarize what I want to achieve. My goal is to have a general table structure to store "any" kind of data, and to make it... describe itself, to get a custom table as output of the query.

Tengo una mesa con esta estructura:

id (INT)
idItem (INT)
fieldTitle (VARCHAR)
field (VARCHAR)
value_label (VARCHAR)
value_text (TEXT)
value_bool (TINYINT)
value_int (INT)
value_float (FLOAT)

An example of the data inside the table:

id  idItem  fieldTitle  field       value_label     value_text              value_bool  value_int   value_float
--------------------------------------------------------------------------------------------------------------
1   15      title       value_label My Product One  NULL                    NULL        NULL        NULL
2   15      description value_text  NULL            Very good product...    NULL        NULL        NULL
3   15      visible     value_bool  NULL            NULL                    1           NULL        NULL
4   15      price       value_float NULL            NULL                    NULL        NULL        19.9
5   16      title       value_label My Product Two  NULL                    NULL        NULL        NULL
6   16      description value_text  NULL            Just an hidden product. NULL        NULL        NULL
7   16      visible     value_bool  NULL            NULL                    0           NULL        NULL
8   16      price       value_float NULL            NULL                    NULL        NULL        30

I want to end having something like this:

idItem (INT)
title  (VARCHAR)
description (TEXT)
visible (TINYINT)
price (FLOAT)

Example of the output data:

idItem  title           description             visible price
15      My Product One  Very good product...    1       19.9
16      My Product Two  Just an hidden product. 0       30

preguntado el 10 de marzo de 12 a las 14:03

Solo puedo recomendar en contra doing this. MySQL, the RDBMS, already does basically this to organize itself internally. Dynamic schemas will almost always set you on the road to difficulty and pain, since you won't be able to easily manage key relationships, indexing, or other RDBMS features. -

Dynamic schemas will almost always set you on the road to difficulty and pain -> I absolutely agree. The proof that you are already on that road is that you had to get very simple information and you needed to ask StackOverflow :) -

Thanks for the first answers and comments! My problem is that I don't want to start with a "fixed set" of fields in my table because I'm developing a CMS where the admin will add his custom fields (that can be lables, long texts, yes/no, etc) and to create his custom "collections" (e.g.: products, contacts, news...), so I can't predict which and how many columns I must insert. Maybe it's better to create una mesa for every kind of data (booleans, ints, texts), with a foreign key to connect elements to their collection? -

2 Respuestas

Although I don't agree with this kind of schemas (see my comment below your question) you can give this a try:

select idItem,
  max(if(fieldTitle = 'title', value_label, null)) Title,
  max(if(fieldTitle = 'description', value_text, null)) Description,
  max(if(fieldTitle = 'visible', value_bool, null)) Visible,
  max(if(fieldTitle = 'price', value_float, null)) Price
from t
group by idItem

Esto resulta en:

+--------+----------------+-------------------------+---------+-------+
| IDITEM |     TITLE      |       DESCRIPTION       | VISIBLE | PRICE |
+--------+----------------+-------------------------+---------+-------+
|     15 | My_Product_One | Very_good_product...    |       1 | 19.9  |
|     16 | My_Product_Two | Just_an_hidden_product. |       0 | 30    |
+--------+----------------+-------------------------+---------+-------+

Adding more fields is straight forward. Let me know if you have ay issues with it.

respondido 10 mar '12, 14:03

Firstly, I agree with the views from Michael and Mosty. Why do you prefer to have a general table for storing all data rather than having specific tables? A table structure like below will keep your data better organised and your queries simpler.

id INT
title VARCHAR(255)
description TEXT
visible TINYINT
price DECIMAL(5,2)

Secondly, assuming that you work with your structure, the below query might help with retrieving data:

SELECT `t`.`idItem`, `t`.`value_label` AS `title`, `t1`.`value_text` AS `description`, `t2`.`value_bool` AS `visible`, `t3`.`value_float` AS `price`
FROM `your_table` `t`
INNER JOIN `your_table` `t1` ON `t`.`idItem` = `t1`.`idItem` AND `t1`.`fieldTitle` = 'description'
INNER JOIN `your_table` `t2` ON `t`.`idItem` = `t2`.`idItem` AND `t2`.`fieldTitle` = 'visible'
INNER JOIN `your_table` `t3` ON `t`.`idItem` = `t3`.`idItem` AND `t3`.`fieldTitle` = 'price'
WHERE `t`.`fieldTitle` = 'title';

Espero eso ayude.

respondido 10 mar '12, 16:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.