首页 > 解决方案 > MySQL - GROUP_CONCAT 在连接多个表时消除重复

问题描述

SQLFiddle在这里

问题:

由于我要加入两个表 -pricesvideos,GROUP_CONCAT()为第二个加入的每一行重复值LEFT JOIN

我的尝试:

SELECT
    `Cat`.*,
    GROUP_CONCAT(COALESCE(`Price`.`id`, "") ORDER BY `Price`.`price`) AS `PriceId`,
    GROUP_CONCAT(COALESCE(`Price`.`price`, "") ORDER BY `Price`.`price`) AS `PricePrice`,
    GROUP_CONCAT(COALESCE(`Vid`.`id`, "") ORDER BY `Vid`.`id`) AS `VideoId`,
    GROUP_CONCAT(COALESCE(`Vid`.`uuid`, "") ORDER BY `Vid`.`id`) AS `VideoUUID`
FROM
    `categories` AS `Cat`
LEFT JOIN `prices` AS `Price` ON `Cat`.`id`=`Price`.`category_id`
LEFT JOIN `videos` AS `Vid` ON `Cat`.`id`=`Vid`.`category_id`
GROUP BY
    `Cat`.`id`

问题:

如何调整查询,因此PricePrice, SQLFiddle 输出VideoIdVideoUUID的列不包含重复项?

我确实尝试DISTINCT在内部添加GROUP_CONCAT,但这没有帮助,因为它会过滤掉我应该保留的重复值(比如,price

谢谢!

标签: mysqlsqljoin

解决方案


一个好的解决方案是使用标量子查询,而不是连接三个表。例如:

select
  *,
  (select group_concat(p.id order by p.price) 
   from prices p where p.category_id = c.id) as PriceId,
  (select group_concat(p.price order by p.price) 
   from prices p where p.category_id = c.id) as PricePrice,
  (select group_concat(v.id order by v.id) 
   from videos v where v.category_id = c.id) as VideoId,
  (select group_concat(v.uuid order by v.id) 
   from videos v where v.category_id = c.id) as VideoUUID
from categories c
group by id

结果:

id  token                PriceId     PricePrice           VideoId      VideoUUID                           
--- -------------------- ----------- -------------------- ------------ ----------------------------------- 
1   Wyatt Reinger (ZW)   2,1,3       2.51,2.61,4.45       1,2,3,4      3a817d01,3222679e,63cdc038,e8d8edf4 
2   Donna Cronin (BL)    4           4.76                 5            93f8a404                            
3   Ally Kertzmann (GY)  5,6         1.83,1.84            6,7,8        6f2459a7,463127ab,4bf357ba          
4   Talia Torp (AF)      7,8         2.61,3.32            9,10,11,12   0cedbd0a,8b21afd7,ea616692,ed2b10d7 
5   Delphine Lakin (TL)  11,12,9,10  1.65,3.27,3.27,3.36  13,14,15,16  6217a488,7f52a97a,de11ba64,b49b6ddc 

请参阅SQL Fiddle上的运行示例。

连接三个表的问题是它会产生许多使聚合复杂化的重复值。


推荐阅读