Ver Mensaje Individual
  #16 (permalink)  
Antiguo 22/07/2009, 09:08
Avatar de huesos52
huesos52
Colaborador
 
Fecha de Ingreso: febrero-2009
Ubicación: Manizales - Colombia
Mensajes: 5.980
Antigüedad: 15 años, 2 meses
Puntos: 360
Respuesta: FAQ's de MySQL

Pregunta: Como puedo agrupar en un solo registro todos los valores para un campo determinado?
Respuesta: Con la función group_concat

Ejemplo:

Código mysql:
Ver original
  1. mysql> create table persona_deporte(persona varchar(20),deporte varchar(20));
  2. Query OK, 0 rows affected (0.06 sec)
  3.  
  4. mysql> insert into persona_deporte values('Daniel','Futbol');
  5. Query OK, 1 row affected (0.00 sec)
  6.  
  7. mysql> insert into persona_deporte values('Daniel','Baloncesto');
  8. Query OK, 1 row affected (0.00 sec)
  9.  
  10. mysql> insert into persona_deporte values('Daniel','valley ball');
  11. Query OK, 1 row affected (0.00 sec)
  12.  
  13. mysql> insert into persona_deporte values('Juan','Tennis');
  14. Query OK, 1 row affected (0.00 sec)
  15.  
  16. mysql> insert into persona_deporte values('Juan','Futbol');
  17. Query OK, 1 row affected (0.00 sec)
  18.  
  19. mysql> insert into persona_deporte values('Santiago','Waterpolo');
  20. Query OK, 1 row affected (0.00 sec)
  21.  
  22. mysql> insert into persona_deporte values('Santiago','Baloncesto');
  23. Query OK, 1 row affected (0.00 sec)
  24.  
  25. mysql> select *from persona_deporte;
  26. +----------+-------------+
  27. | persona  | deporte     |
  28. +----------+-------------+
  29. | Daniel   | Futbol      |
  30. | Daniel   | Baloncesto  |
  31. | Daniel   | valley ball |
  32. | Juan     | Tennis      |
  33. | Juan     | Futbol      |
  34. | Santiago | Waterpolo   |
  35. | Santiago | Baloncesto  |
  36. +----------+-------------+
  37. 7 rows in set (0.00 sec)
  38.  
  39. mysql> select persona,group_concat(deporte separator " - ") deportes from persona_deporte group by persona;
  40. +----------+-----------------------------------+
  41. | persona  | deportes                          |
  42. +----------+-----------------------------------+
  43. | Daniel   | Futbol - Baloncesto - valley ball |
  44. | Juan     | Tennis - Futbol                   |
  45. | Santiago | Waterpolo - Baloncesto            |
  46. +----------+-----------------------------------+
  47. 3 rows in set (0.00 sec)
__________________
Without data, You are another person with an opinion.
W. Edwads Deming