sql >> Base de Datos >  >> RDS >> Mysql

mySQL>> Agregar enlaces HREF a un GROUP_CONCAT distinto

Siguiendo con esta pregunta y usando esa consulta como base para el siguiente ejemplo, puede hacer esto con lo siguiente:

SELECT 
CONCAT(res_id,': ',res_name) 'Resources', 
GROUP_CONCAT(distinct t_name order by t_id separator ',') 'Topics', 
GROUP_CONCAT(distinct ch_name order by ch_id separator ',') 'Chapters'
FROM (SELECT res_id,
      res_name,
      t_id,
      t_name,
      ch_id, 
      CONCAT("<a href=\"page.asp?topic=",ch_name,"\" title=\"",ch_name,"\">",ch_name,"</a>") as ch_name 
             FROM resources r
             JOIN topics_to_resource ttr ON ttr.tr_resid = r.res_id
             JOIN topics t on t.t_id = ttr.tr_tid
             JOIN topics_to_chapter ttc on ttc.tch_tid = t.t_id
             JOIN chapters ch ON ch.ch_id = tch_chid) links
      GROUP BY res_id
      ORDER BY res_id, t_id, ch_id;

Básicamente, envolví los datos de origen en una (sub) consulta separada, construí los enlaces y luego realicé el GROUP_CONCAT está fuera de esto.

Esto produce:

<a href="page.asp?topic=CHAPTER #1" title="CHAPTER #1">CHAPTER #1</a>,
<a href="page.asp?topic=CHAPTER #2" title="CHAPTER #2">CHAPTER #2</a>,
<a href="page.asp?topic=CHAPTER #3" title="CHAPTER #3">CHAPTER #3</a>

Ver este violín para más detalles