繁体   English   中英

MySQL - GROUP_CONCAT 在加入多个表时消除重复

[英]MySQL - GROUP_CONCAT eliminate duplicates when joining multiple tables

SQLFiddle在这里

问题:

由于我要加入两个表 - pricesvideosGROUP_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中的 PricePrice 、 VideoIdVideoUUID列不包含重复项?

我确实尝试在GROUP_CONCAT中添加DISTINCT ,但这无济于事,因为它会过滤掉我应该保留的重复值(例如price

谢谢!

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

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的运行示例。

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

有时您只需要接受并非所有问题都应该在一个查询中解决。 在这种情况下,您可以通过执行两个单独的查询来避免两个连接表之间的笛卡尔积:

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

SELECT
    `Cat`.*,
    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 `videos` AS `Vid` ON `Cat`.`id`=`Vid`.`category_id`
GROUP BY
    `Cat`.`id`;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM