来自mysql查询的重复结果

时间:2019-06-06 07:33:46

标签: mysql

执行查询后,尝试获取树结构类别ID时,将得到重复的ID。 我们期望输出没有重复的ID

myshell> bash
bash-3.2$ exit
exit

实际输出:

SELECT 
  GROUP_CONCAT(CONCAT_WS(',',t1.CategoryID,t2.CategoryID,t3.`CategoryID`, t4.CategoryID)) AS id 
FROM prodcategory AS t1 
LEFT JOIN prodcategory AS t2 ON t2.ParentCategoryID = t1.CategoryID 
LEFT JOIN prodcategory AS t3 ON t3.ParentCategoryID = t2.CategoryID 
LEFT JOIN prodcategory AS t4 ON t4.ParentCategoryID=t3.CategoryID 
WHERE t1.ParentCategoryID =41

预期输出:

190,256,190,257,191,261,300,191,262,192,267

样本数据库数据:

190,256,257,191,261,300,262,192,267

1 个答案:

答案 0 :(得分:0)

您可以使用DISTINCT关键字重复显示结果。

    SELECT GROUP_CONCAT(CONCAT_WS(',',DISTINCT 
    t1.CategoryID,DISTINCT t2.CategoryID,DISTINCT t3.`CategoryID`,DISTINCT  
    t4.CategoryID)) AS id FROM prodcategory AS t1 
    LEFT JOIN prodcategory AS t2 ON t2.ParentCategoryID = t1.CategoryID 
    LEFT JOIN prodcategory AS t3 ON t3.ParentCategoryID = t2.CategoryID 
    LEFT JOIN prodcategory AS t4 ON t4.ParentCategoryID=t3.CategoryID 
    WHERE t1.ParentCategoryID =41