2010-05-28 7 views
1
  • poste (id_post, titre)
  • tag (id_tag, nom)
  • post_tag (id_post_tag, id_post, id_tag)

laisse supposer que id_post 3 a 4 tags liés 1,2,3,4 (football, basket, tennis et golf).mysql: obtenir toutes les lignes dans 1 colonne

Existe-t-il un moyen de retourner quelque chose comme ça dans UNE ligne?

  • col 1 id_post = 3
  • col 2 tags = football panier de tennis de golf

Merci

Répondre

2

Utilisation:

SELECT p.id_post 
     GROUP_CONCAT(DISTINCT t.name SEPARATOR ' ') 
    FROM POST p 
    JOIN POST_TAG pt ON pt.id_post = p.id_post 
    JOIN TAG t ON t.id_tag = pt.id_post_tag 
GROUP BY p.id_post 

Soyez conscient que la défaut s eparator est une virgule, vous devez donc définir un seul espace si vous ne le souhaitez pas entre les noms de tag.

Documentation:

+0

fonctionnait très bien! juste un doute de plus ... comment puis-je limiter la quantité de tags, par exemple: 3 - j'ai essayé d'utiliser une approche LIMIT mais ça ne marchera pas. – andufo

+0

@andufo: Vous devez utiliser une variable pour fournir une fonctionnalité analytique car elle n'existe pas dans MySQL. –

Questions connexes