mysql - MySQL - GROUP_CONCAT 在连接多个表时消除重复
问题描述
问题:
由于我要加入两个表 -prices
和videos
,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 输出VideoId
中VideoUUID
的列不包含重复项?
我确实尝试DISTINCT
在内部添加GROUP_CONCAT
,但这没有帮助,因为它会过滤掉我应该保留的重复值(比如,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上的运行示例。
连接三个表的问题是它会产生许多使聚合复杂化的重复值。
推荐阅读
- php - 无法在 Windows Server 2016 上加载 pdo 驱动程序
- python - 在 Datetime 上合并两个数据集
- android - 添加发布方法(MediaPlayer)后应用无法运行
- javascript - 在本地将 XSLT 应用于 XML,无需服务器
- javascript - Leaflet图层控件中图层的排序顺序
- clojure - 如何将profiles.clj 加载到CURSIVE REPL 中?
- r - 使用输入在 Shiny 中分配名称
- batch-file - Windows 批量比较固定日期和当前日期
- qt - 是否可以直接使用 QtDesigner 实现独立于分辨率的 UI?
- javascript - 为什么我收到错误“Uncaught TypeError: Cannot read property 'style' of undefined at HTMLLIElement.”?