mySQL>>将HREF链接添加到不同的GROUP_CONCAT

时间:2017-10-08 01:04:11

标签: mysql distinct concat group-concat

我有以下查询:

SELECT *, RES.res_id 'ID', RES.RES_Title 'Title', 
GROUP_CONCAT(DISTINCT T.T_Name separator ', ') 'Topics', 
GROUP_CONCAT(DISTINCT CH.CH_Code separator ', ') 'Chapters' 
FROM Resources RES 
LEFT JOIN topic_to_resource RT ON RT.RT_ResourceID = RES.RES_ID 
LEFT JOIN topics T on T.T_ID = RT.RT_TopicID 
LEFT JOIN topic_to_chapter TCH on TCH.TCH_TopicID = T.T_ID 
LEFT JOIN chapters CH ON CH.CH_ID = TCH.TCH_FrameworkID 
WHERE RES_Status = 'Active' 
GROUP BY RES.RES_ID 
ORDER BY RES_Title ASC, RES_Source DESC LIMIT 0, 10

对于每个GROUP_CONCAT(主题和章节),我需要将列表转换为链接,同时保持Distinct。

例如,代替上述查询的主题输出:体育,时事,政治,气候等

我需要生成:

<a href="page.asp?topic=Sports" title="Sports">Sports</a>, 
<a href="page.asp?topic=Current%20Events" title="Current Events">Current Events</a>, 
<a href="page.asp?topic=Politics" title="Politics">Politics</a>, 
<a href="page.asp?topic=Climate" title="Climate">Climate</a>

我可以通过在GROUP_CONCAT中嵌套CONCAT来实现链接,但后来我失去了Distinct。此外,我需要查询保持按资源ID(RES.RES_ID)分组。

关于如何完成不同主题和章节的链接列表的任何想法?

非常感谢提前!

1 个答案:

答案 0 :(得分:0)

this question开始,并使用该查询作为以下示例的基础,您可以执行以下操作:

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;

基本上我已将源数据包装在单独的(子)查询中,构建链接,然后在此之外执行GROUP_CONCAT

这会产生:

enter image description here

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

有关详细信息,请参阅this fiddle