Mysql
 sql >> Datenbank >  >> RDS >> Mysql

mySQL>> Hinzufügen von HREF-Links zu einem Distinct GROUP_CONCAT

Im Anschluss an diese Frage , und indem Sie diese Abfrage als Grundlage für das folgende Beispiel verwenden, können Sie dies folgendermaßen tun:

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;

Grundsätzlich habe ich die Quelldaten in eine separate (Unter-)Abfrage verpackt, die Links erstellt und dann den GROUP_CONCAT ausgeführt ist außerhalb davon.

Dies erzeugt:

<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>

Siehe diese Geige für mehr Details