la base de datos está estructurada de la siguiente manera:
id | meta-key | meta-value 1 | client | John 1 | bday | todayquiero que sea
id | client | bday 1 | John | todayhay muchas líneas como client y bday y quiero transformar algunas de ellas en columnas, ya sea al mostrarlas o al insertarlas en otra tabla
Intenté algo como esto:
SELECT p1.meta_value, wph0_posts.post_title, p2.meta_value as client, p3.meta_value as end_date, p4.meta_value as description FROM wph0_postmeta p1 INNER JOIN wph0_posts ON p1.post_id = wph0_posts.ID INNER JOIN wph0_postmeta p2 ON p1.post_id = p2.post_id AND p2.meta_key = 'client' INNER JOIN wph0_postmeta p3 ON p1.post_id = p3.post_id AND p3.meta_key = 'end_date' INNER JOIN wph0_postmeta p4 ON p1.post_id = p4.post_id AND p4.meta_key = 'description';¿puedo obtener algunos consejos? bastante nuevo en db'es
CREATE TABLE wph0_postmeta ( `id` INTEGER, `meta-key` VARCHAR(20), `meta-value` VARCHAR(20) ); INSERT INTO wph0_postmeta (`id`, `meta-key`, `meta-value`) VALUES ('1', 'client', 'John'), ('1', 'bday', 'today'), ('1', 'descriptiuon', 'test'), ('2', 'client', 'Jerry'), ('2', 'bday', 'tomorrow'), ('2', 'descriptiuon', 'secondtest');
INSERT INTO wph0_postmeta (`id`, `meta-key`, `meta-value`) VALUES ('1', 'client', 'John'), ('1', 'bday', 'today'), ('1', 'descriptiuon', 'test'), ('2', 'client', 'Jerry'), ('2', 'bday', 'tomorrow'), ('2', 'descriptiuon', 'secondtest');
CREATE TABLE wph0_posts ( id INT, post_title varchar(20)); INSERT INTO wph0_posts VALUES (1,'Dr.Dr.'),(2,'Prof.Dr.Dr.')
SELECT t1.id, t2.post_title ,MAX(IF(t1.`meta-key` = 'client', t1.`meta-value`,NULL)) 'client' ,MAX(IF(t1.`meta-key` = 'bday', t1.`meta-value`,NULL)) 'birthday' ,MAX(IF(t1.`meta-key` = 'descriptiuon', t1.`meta-value`,NULL)) 'descriptiuon' FROM wph0_postmeta t1 INNER JOIN wph0_posts t2 ON t1.id = t2.id GROUP BY t1.id,t2.post_titleidentificación | post_título | cliente | cumpleaños | descripción -: | :----------- | :----- | :------- | :----------- 1 | Dr. Dr. | Juan | hoy | prueba 2 | Prof.Dr.Dr. | jerry | mañana | segunda prueba
db<>violín aquí
Esto funciona para un conjunto fijo de valor perfecto. pero si tiene mucho más y diferente, debe mirar la consulta MySQL para crear una tabla dinámica uniendo 4 tablas diferentes
Gracias por la ayuda, lo siguiente funcionó:
SELECT wph0_postmeta.post_id, GROUP_CONCAT( if(wph0_postmeta.meta_key='client',wph0_postmeta.meta_value,NULL) ) AS Nume, GROUP_CONCAT( if(wph0_postmeta.meta_key='end_date',wph0_postmeta.meta_value,NULL) ) AS Descriere FROM wph0_postmeta GROUP BY wph0_postmeta.post_idSolo extraje el nombre y algunas cosas de wph0_postmeta y usé la declaración if. Ahora puedo agregar otro group_concat y agregar otra columna desde meta_key, obtuve el enlace para pivotes aquí: