2

I have a MySQL question, and really have no Idea how to resolve it.

I have the following query:

SELECT p.nombre, ti.tallerhorario_id FROM persona p, talleresinscritos ti WHERE p.pasaporte = ti.pasaporte

At the result is this:

enter image description here

I'm looking to make a query in which the second column doesn't show as a row for every "tallerhorario_id", but for every "nombre".

For example:

EUCLIDES | 7 | 24 | 32 | 48

LIZ LORENA | 4 | 18 | 33 | 47

Every person always have 4 rows associated, without exceptions.

Could you help me please?

Thank you!

1

1 Answer 1

2

The simplest method is to actually put the values in one column, using group_concat():

SELECT p.nombre, group_concat(ti.tallerhorario_id) FROM persona p JOIN -- LEARN TO USE PROPER EXPLICIT JOIN SYNTAX talleresinscritos ti ON p.pasaporte = ti.pasaporte GROUP BY p.nombre; 

A comma-delimited list is not what you asked for, but it might solve your problem. If you have an counter, say 1, 2, 3, and 4, the second table, then you can easily do this using conditional aggregation:

SELECT p.nombre, MAX(case when counter = 1 then ti.tallerhorario_id end) as id1, MAX(case when counter = 2 then ti.tallerhorario_id end) as id2, MAX(case when counter = 3 then ti.tallerhorario_id end) as id3, MAX(case when counter = 4 then ti.tallerhorario_id end) as id4 FROM persona p JOIN -- LEARN TO USE PROPER EXPLICIT JOIN SYNTAX talleresinscritos ti ON p.pasaporte = ti.pasaporte GROUP BY p.nombre; 

Finally, if you don't have a counter, one way is to add one uses variables:

SELECT p.nombre, MAX(case when counter = 1 then ti.tallerhorario_id end) as id1, MAX(case when counter = 2 then ti.tallerhorario_id end) as id2, MAX(case when counter = 3 then ti.tallerhorario_id end) as id3, MAX(case when counter = 4 then ti.tallerhorario_id end) as id4 FROM persona p JOIN -- LEARN TO USE PROPER EXPLICIT JOIN SYNTAX (SELECT ti.*, (@rn := if(@p = pasaporte, @rn + 1 if(@p := pasaporte, 1, 1) ) ) as counter FROM talleresinscritos ti CROSS JOIN (SELECT @p := '', @rn := 0) params ORDER BY ti.pasaporte ) ti ON p.pasaporte = ti.pasaporte GROUP BY p.nombre; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.